Correct way to write loops for promise.

后端 未结 13 1907
猫巷女王i
猫巷女王i 2020-11-22 15:20

How to correctly construct a loop to make sure the following promise call and the chained logger.log(res) runs synchronously through iterat

13条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 15:30

    Here's how I do it with the standard Promise object.

    // Given async function sayHi
    function sayHi() {
      return new Promise((resolve) => {
        setTimeout(() => {
          console.log('Hi');
          resolve();
        }, 3000);
      });
    }
    
    // And an array of async functions to loop through
    const asyncArray = [sayHi, sayHi, sayHi];
    
    // We create the start of a promise chain
    let chain = Promise.resolve();
    
    // And append each function in the array to the promise chain
    for (const func of asyncArray) {
      chain = chain.then(func);
    }
    
    // Output:
    // Hi
    // Hi (After 3 seconds)
    // Hi (After 3 more seconds)
    

提交回复
热议问题