weixin_33738578 2019-10-10 11:20 采纳率: 0%
浏览 96

Javascript promise.all()

I have this piece of code.

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")

Here, we get the output

"here"

and then after two seconds, we get

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

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?

Hence, the output I want is

Wait two seconds and see

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

"here"

  • 写回答

4条回答 默认 最新

  • weixin_33717117 2019-10-10 11:29
    关注

    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") });
    

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

    评论

报告相同问题?