我想更多地理解 promise ,但我不能很好地理解这个想法...... 假设我有这个示例程序:
var anArray = [];
for (var i = 1; i < 30; i++) {
var lastPage = i - 1;
unirest.post('https://www.example.com/')
.header('Accept', 'application/json')
.send({
"command": 'page[' + i + ']',
"url": "[" + lastPage + "]"
})
.end(function (response) {
// add result to anArray
});
}
//do stuff with anArray when all are done..
unirest 的回调将以异步模式调用,所以你不知道它什么时候会得到结果,什么时候结束。
当它全部完成时,我如何在最后记录它?
有没有办法通过 promises 检查响应来打破循环?
最佳答案
这是使用 ES6 promises 的一种方法(也适用于 Bluebird):
var promises = [];
for (var i = 1; i < 30; i++) {
promises.push(new Promise(function(resolve, reject) {
var lastPage = i - 1;
unirest.post('https://www.example.com/')
.header('Accept', 'application/json')
.send({
"command": 'page[' + i + ']',
"url": "[" + lastPage + "]"
})
.end(function (response) {
resolve(response);
});
}));
}
Promise.all(promises).then(function(results) {
// all promises are fulfilled here
// results is an array of all the responses, in order
}, function(err) {
// one or more promises rejected, err is the first rejection reason
});
仅供引用,这会同时运行所有 29 个请求(它们都会立即发送并同时发送到服务器)。我假设这就是您想要的。
您还可以使用一些 Bluebird 的集合迭代函数,例如 Bluebird.map()
来直接迭代数组。
而且,如果您要使用带有 promise 的 unirest
接口(interface),您可能想弄清楚如何 promise 该接口(interface),以便您拥有一个内置 promise 的版本,这样您可以那样使用它,而不是每次你想使用它时都必须对它做出 promise 。我不太了解该接口(interface)是如何工作的,无法建议如何在这里 promise 它,所以我只是让你的一组命令与 promise 一起工作。
关于javascript - bluebird 在一个简单的 for 循环中 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32737108/