How to structure nested Promises

前端 未结 3 1096
误落风尘
误落风尘 2020-11-30 12:00

I have a situation where I think the only choice for me is to nest some Promises within each other. I have a Promise that needs to be performed and a method that does someth

3条回答
  •  忘掉有多难
    2020-11-30 12:54

    Each function will call the next one with the result of the method before.

    var promises = [1,2,3].map((guid)=>{
        return (param)=> {
          console.log("param", param);
          var id = guid;
          return new Promise(resolve => {
            // resolve in a random amount of time
            setTimeout(function () {
              resolve(id);
            }, (Math.random() * 1.5 | 0) * 1000);
          });
        }
    }).reduce(function (acc, curr, index) {
      return acc.then(function (res) {
        return curr(res[index-1]).then(function (result) {
          console.log("result", result);
          res.push(result);
          return res;
        });
      });
    }, Promise.resolve([]));
    promises.then(console.log);
    

提交回复
热议问题