获得一系列未决承诺 [英] Getting an array of pending promises

查看:93
本文介绍了获得一系列未决承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆