Dynamic Chaining in Javascript Promises

后端 未结 8 1368
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 20:42

How can I perform dynamic chaining in Javascript Promises, all the time I have seen only hardcoding of the calls for eg., (promise).then(request/funct

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-08 21:09

    This is ES7 way.

    Let's say you have multiple promises defined in an array.

      var funcs = [
        _ => new Promise(res => setTimeout(_ => res("1"), 1000)),
        _ => new Promise(res => setTimeout(_ => res("2"), 1000))
      }
    

    And you want to call like this.

     chainPromises(funcs).then(result => console.log(result));
    

    You can use async and await for this purpose.

      async function chainPromises(promises) {
        for (let promise of promises) {  // must be for (.. of ..)
          await promise();
        }
      }
    

    This will execute the given functions sequentially(one by one), not in parallel. The parameter promises is an array of functions, which return Promise.

    Plunker: http://plnkr.co/edit/UP0rhD?p=preview

提交回复
热议问题