获得一系列未决承诺 [英] Getting an array of pending promises
问题描述
var arr = [1,2 ,3, 4, 5, 6, 67, 8, 10];
function f1 () {
return arr.map(function (member) {
console.log(member);
return Promise.resolve(member + 2).then((result) => {return result + 2}).then
(value => {return value + 1});
});
}
console.log(f1());
输出数组为 Promise {< pending>每个索引都有
。有什么问题?我认为返回值+ 1
最终解决了承诺,为什么我要等待?
The output is an array of Promise { <pending> }
at every single index. What is the issue? I thought the return value + 1
at the end resolved the promises, so why am I getting pending?
推荐答案
代码没有问题,预计会发生什么。
There is no issue with the code, what happens is expected.
我认为
返回值+ 1
最后解决了承诺
不,这不是 return
本身,它是然后
功能,它将使用回调函数的返回值来解析promise。
No, it's not the return
itself, it's the then
functionality that will resolve the promise with the return value of the callback function.
不,它还没有解决承诺,将解决未来的承诺 。 然后
回调总是异步调用。
And no, it didn't resolve the promise yet, it will resolve the promises in the future. then
callbacks are always called asynchronously.
为什么我要等待?
so why am I getting pending?
因为当你记录它们时它们仍处于未决状态;之后会立即解决。
Because the are still pending when you log them; they will get resolved immediately afterwards.
如果要记录结果数组,请使用
If you want to log an array of the results, use
Promise.all(f1()).then(console.log);
这篇关于获得一系列未决承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!