【发布时间】:2019-09-29 21:07:03
【问题描述】:
我正在尝试使用 async await 在 map 函数中理解 Promise.all,但我似乎返回了未决的承诺,我不明白为什么
这是当我有一个 .then 来解决我的承诺时的工作代码
const arr = [1, 2, 3, 4, 5];
const results = Promise.all(arr.map( item => {
return item + 1;
}));
results.then(result=> console.log(result))
按预期记录 = [ 2, 3, 4, 5, 6 ]
现在要使用 async-await 来实现该函数,我知道我需要使用关键字 async 将函数包装在一个异步函数中并等待 promise.all
const results = async () => await Promise.all(arr.map(async (item) => {
return item + 1;
}));
console.log(results())
但我似乎总是登录 Promise { <pending> } 我不明白我做错了什么
【问题讨论】:
-
你不能像这样使用 async with map。抱歉,我正在打电话,所以明天我可能会给你一个解决方案。我之前偶然发现了这个问题并修复了它
-
你必须等待结果
console.log(await results()) -
您实际上并没有在此处执行任何异步操作,因此不需要 promise 或
async/await。但基本上async的全部目的是强制一个函数返回一个promise,所以它的返回值确实是一个promise 也就不足为奇了!
标签: javascript node.js promise async-await