javascript - 我可以在不使用计数变量的情况下解决 asyncMap 吗?

标签 javascript asynchronous async-await

有没有一种方法可以在不使用计数器变量的情况下编写下面的函数来知道超时何时完成。

可以使用 async/await 来完成吗?

我在下面提供了测试调用和当前工作函数。

// write asyncMap below such that results array holds
// ['one', 'two', 'three']
// when the callback results function is run
// asyncMap has the prototype asyncMap(callbackArray, resultsCallbck)

asyncMap([
    (cb) => {
      setTimeout(() => {
        cb('one');
      }, 200);
    },
    (cb) => {
      setTimeout(() => {
        cb('two');
      }, 300);
    },
    (cb) => {
      setTimeout(() => {
        cb('three');
      }, 100);
    }
  ],
  (results) => {
    console.log(results); // ['one', 'two', 'three]
  }
);


//
//
function asyncMap(tasks, callback) {
  const results = [];
  let count = 0;
  for (let i = 0; i < tasks.length; i++) {
    const func = tasks[i];
    // await runFunc();
    function cb (val) {
      results[i] = val;
      count++;
      console.log(i, count);
      if (count === tasks.length) {
        callback(results);
      }
    }
    func(cb);
  }
};

最佳答案

这比您想象的要容易得多。

您只需要 Promise.all .

在不改变你调用asyncMap的方式的情况下,你可以这样做:

/* Nothing changes here */
asyncMap([
    (cb) => {
      setTimeout(() => {
        cb('one');
      }, 200);
    },
    (cb) => {
      setTimeout(() => {
        cb('two');
      }, 300);
    },
    (cb) => {
      setTimeout(() => {
        cb('three');
      }, 100);
    }
  ],
  (results) => {
    console.log(results); // ['one', 'two', 'three]
  }
);

/* Reduced the whole function into only 3 lines */
function asyncMap(tasks, callback){
  tasks = tasks.map(cb => new Promise(cb))
  return Promise.all(tasks)
    .then(callback);
}

关于javascript - 我可以在不使用计数变量的情况下解决 asyncMap 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57300667/

相关文章:

javascript - 运行 Google Script 网络应用程序后关闭窗口?

javascript - 有没有办法读取服务器上的文件而无需在 Node js中下载?

javascript - 将 jquery 转换为 prototype.js 以在向下滚动时将 scrollTop 等效更改为标题

javascript - 无法填充数组并返回

c# - 公开可取消任务 API 的正确方法

javascript - Meteor用户访问数据时未定义

javascript - 如何在 RxJS 中按功能组合函数( f(g(h)))?

Ios Firebase 异步登录

javascript - 在使用错误返回异步函数时,避免 Node.JS 中的回调 hell 的常见做法有哪些?

c# - 如何确保多个异步下载的数据按照开始的顺序保存?