两个不同的动态承诺提供者链之间的对等

时间:2018-07-13 04:34:20

标签: javascript node.js async-await es6-promise

我想知道两个代码块是否基本相等:

const executePromises = function(listOfProviders){

    let p = Promise.resolve(null);

    for(let i = 0; i < listOfProviders.length; i++){
       p = p.then(v => listOfProviders[i]());
    }

   return p;

};

我相信以上内容基本上等同于:

const executePromises = async function(listOfProviders) {

    for(let i = 0; i < listOfProviders.length; i++){
       await listOfProviders[i]();
    }

};

有人看到差异吗?

1 个答案:

答案 0 :(得分:2)

否。它们不一样。即使您按照某人在评论中指出的那样兑现了诺言。

差异:

  • async awaitfor-loop一起使用时,应该记住,只有在当前迭代中已解决了等待的诺言时,for循环才会进入下一个迭代。
  • 另一方面,当在.then中使用for-loop时,for-loop在等待下一次迭代之前不会等待promise分解。

我已经对您的代码进行了调整以证明这一点。观察每个代码段中的不同时间点正在调用 Line A

Async await代码内的

for-loop

function createPromiseWhichResolveAfterOneSec(i) {
    return new Promise((resolve, reject)=>{
        setTimeout(()=>{
            console.log("About to resolve promise with value:",i);//Line A
            resolve(i);
        },1000)
    })
}

const executePromises = async function(listOfProviders) {

    let p;
    let i;
    for(i = 0; i < listOfProviders.length; i++){
        console.log("before", i);
        p = await createPromiseWhichResolveAfterOneSec(i);
        console.log("after", i);
    }
    console.log(i);
    return p;

};


let listOfProviders = [1,2,3,4,5];
let promise = executePromises(listOfProviders);
promise.then(value => console.log("this is the final value of promise chain:",value)).catch(()=>{});

then中有for-loop

function createPromiseWhichResolveAfterOneSec(i) {
    return new Promise((resolve, reject)=>{
        setTimeout(()=>{
            console.log("About to resolve promise with value:",i);//Line A
            resolve(i);
        },1000)
    })
}


const executePromises = function(listOfProviders){

    let p = Promise.resolve(null);

    for(let i = 0; i < listOfProviders.length; i++){
        console.log("before", i);
        p = p.then(v => createPromiseWhichResolveAfterOneSec(i));
        console.log("after", i);
    }

    return p;

};

let listOfProviders = [1,2,3,4,5];
let promise = executePromises(listOfProviders);
promise.then(value => console.log("this is the final value of promise chain:",value)).catch(()=>{});