【问题标题】:Using async with map to execute multiple promises使用 async with map 执行多个 Promise
【发布时间】:2021-06-17 20:24:08
【问题描述】:

我正在尝试使用 async with map 执行多个承诺:

const testAsyncFunction = async function testAsyncFunction() {
  const array = ["var1", "var2"];
  const promises = array.map(
    (variable) =>
      async function () {
        // This doesn't get logged
        console.log(
          "???? ~ file: coursesServices.js ~ line 853 ~ testAsyncFunction ~ variable",
          variable
        );
        return variable + "TEST";
      }
  );
  const promises_results = await Promise.all(promises);
  // This gets logged
  console.log(
    "???? ~ file: coursesServices.js ~ line 861 ~ testAsyncFunction ~ promises_results",
    promises_results
  );
};
testAsyncFunction();

这里的问题是 map 函数中的代码永远不会被执行。

这是在控制台中记录的内容:

???? ~ file: coursesServices.js ~ line 861 ~ testAsyncFunction ~ promises_results [ [AsyncFunction (anonymous)], [AsyncFunction (anonymous)] ]

我看不出我到底做错了什么。 但是,我有一种感觉 Promise.all 不适用于异步函数数组。

【问题讨论】:

  • function 不是Promise。在 .map() 回调 (.map(value => new Promise(...)) 中返回显式 Promise 或在回调中执行匿名函数并返回其返回值 (.map(value => (async function() { ... })()))。
  • @Andreas 或者只是在 .map() 中使用异步回调而不是返回异步函数:.map(async (value) => { /* ... */ })

标签: javascript async-await promise es6-promise


【解决方案1】:

您应该在地图内使用 new promise。否则promise.all 不关心地图

(async() => {
  const arr = [1, 2, 3]
  const res = arr.map((a) => {
    return new Promise((resolve) => {
      setTimeout(() => {  //async call
        resolve(a + 'finished')
      }, 1000)
    })
  })
  console.log(await Promise.all(res))
})()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-16
  • 2018-03-27
  • 2021-11-28
  • 2017-10-21
  • 1970-01-01
  • 2019-11-06
  • 1970-01-01
相关资源
最近更新 更多