如何为另一个承诺解决一个承诺

How to Resolve Promise for Another Promise?

本文关键字:一个承诺 解决      更新时间:2023-09-26

标题混乱,对不起。

我需要查看一个承诺的内容,以便后续的承诺。

看到我以前的线程上下文:如何从API顺序处理异步结果?

我有下面的工作代码,我注释了我的问题:

    var promises = [];
    while (count) {
        var promise = rp(options);
        promises.push(promise);
        // BEFORE NEXT PROMISE, I NEED TO GET ID OF AN ELEMENT IN THIS PROMISE'S DATA
        // AND THEN CHANGE 'OPTIONS' 
    }
    Promise.all(promises).then(values => {
        for (var i = 0; i < values; i++) {
            for (var j = 0; j < values[i].length; j++) {
                results.push(values[i][j].text);
            }
        }
        return res.json(results);
    }, function(reason) {
        trace(reason);
        return res.send('Error');
    });

这是一个关于如何链接承诺的完美例子,因为then的结果是一个新的承诺。

while (count) {
    var promise = rp(options);
    promises.push(promise.then(function(result) {
        result.options = modify(result.options);  // as needed
        return result.options;
    });
}

就这样,每个承诺都给了承诺。

如果一个承诺依赖于另一个(例如,它不能执行,直到前一个已经完成并提供了一些数据),那么你需要链接你的承诺。不存在"为了获得一些数据而达成承诺"。如果您想要它的结果,您可以使用.then()等待它。

rp(options).then(function(data) {
    // only here is the data from the first promise available 
    // that you can then launch the next promise operation using it
});

如果你想做这个序列count次(这是你的代码所暗示的),那么你可以创建一个包装器函数,并从每个承诺的完成调用自己,直到达到计数。

function run(iterations) {
     var count = 0;
     var options = {...};   // set up first options
     var results = [];      // accumulate results here
     function next() {
          return rp(options).then(function(data) {
              ++count;
              if (count < iterations) {
                  // add anything to the results array here
                  // modify options here for the next run
                  // do next iteration
                  return next();
              } else {
                  // done with iterations
                  // return any accumulated results here to become
                  // the final resolved value of the original promise
              }
          });
     }
     return next();
}
// sample usage
run(10).then(function(results) {
      // process results here
}, function(err) {
      // process error here
});