Javascript promise.all() [英] Javascript promise.all()

查看:51
本文介绍了Javascript promise.all()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码.

function a() {
  var promise1 = Promise.resolve(3);
  var promise2 = 42;
  var promise3 = new Promise(function(resolve, reject) {
    setTimeout(resolve, 2000, 'foo');
  });

  Promise.all([promise1, promise2, promise3]).then(function(values) {
    console.log("done", values);
  });
}

async function b() {
 await a(); 
}

b();
console.log("here")

在这里,我们得到输出

此处"

然后两秒钟后,我们得到

and then after two seconds, we get

完成";数组[3,42,"foo"]

"done" Array [3, 42, "foo"]

如何更改此代码,以使在函数b()中,我们实际上正在等待a()完成,然后继续执行代码?

How do I change this code so that inside function b(), we are actually waiting for a() to complete and then continue the execution of the code?

因此,我想要的输出是

等待两秒钟,看看

完成";数组[3,42,"foo"]

"done" Array [3, 42, "foo"]

此处"

推荐答案

您可以这样编写上面的代码:

You can write the above code like this:

function a() {
    var promise1 = Promise.resolve(3);
    var promise2 = 42;
    var promise3 = new Promise(function (resolve, reject) {
        setTimeout(resolve, 2000, 'foo');
    });

    // Promise.all([promise1, promise2, promise3]).then(function (values) {
    //     console.log("done", values);
    // });

    return Promise.all([promise1, promise2, promise3]);
}

async function b() {
    let values = await a();
    console.log('done', values);
    // return values; // This will get automatically get wrapped into a promise.
    return Promise.resolve(values);
}

b().then(() => { console.log("here") });

此处 a 返回一个承诺,然后 b 也返回一个立即解决的承诺.

Here a returns a promise and after that b also returns a promise which is immediately resolved.

这篇关于Javascript promise.all()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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