How to structure nested Promises

前端 未结 3 1086
误落风尘
误落风尘 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:45

    Use .then()

    let doStuff = (resolve, reject) => {/* resolve() or reject() */};
    let promise = new Promise(doStuff);
    doSomethingUntilPromiseisDone(
      promise 
      .then(value => fetchValue(url))
      .then(value => value.blob())
      .then(saveToCache)
    )
    .then(success => console.log("success!!"))
    .catch(err => console.error(err))
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-30 12:59

    you can use generator to flatten your nested promises (Bluebird.couroutine or Generators)

    //Bluebird.couroutine
    const generator = Promise.coroutine(function*() {
      try {
         const value = yield fetchValue(url);
         const success = yield saveToCache(value);
         console.log('success:', success);
      } catch(e) {
         console.error(err);
      }    
    }));
    
    generator();
    
    0 讨论(0)
提交回复
热议问题