如何为另一个承诺解决一个承诺
How to Resolve Promise for Another Promise?
标题混乱,对不起。
我需要查看一个承诺的内容,以便后续的承诺。
看到我以前的线程上下文:如何从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
});
相关文章:
- iPad虚拟键盘-哪一个-javasctript解决方案
- RxJS等待承诺解决
- 一个承诺换多个承诺-并发问题
- 执行一系列 Javascript 承诺一个接一个地解决
- WinJS,从可能是异步的函数返回一个承诺,也可能不是异步的
- 在jQuery中,.state()如何确定一个承诺是挂起的、已解决的还是被拒绝的
- 转换嵌套'对于'循环成一个承诺,为了一个承诺?嵌套承诺
- 如何通过Bluebird承诺您自己的javascript api,该api使用另一个承诺的api
- jasmine 2.0测试angularjs的工厂方法,这是一个承诺
- 所有承诺解决后返回
- 做一些 ajax 并使用 getJSON 返回一个承诺
- 在 AngularJS 中声明一个承诺,并带有命名的成功/错误回调
- 链承诺.all 与从上一个承诺返回的数组.all.
- 如何更好地停止一个承诺链并开始另一个承诺链
- 如果你用另一个承诺解决一个承诺会发生什么
- 基于另一个承诺解决承诺
- 返回一个承诺,而不是用angular's $q.then()来解决它
- 在进入下一行之前,我如何确保一个承诺被解决
- 如何使用$q从AngularJS服务返回一个已解决的承诺
- 如何为另一个承诺解决一个承诺