异步调用的同步循环
Synchronous loop with async calls
这是我需要完成的:
我有一个函数(我们称之为 thePromise
),returns 一个承诺。
我有一个包含 运行 thePromise
的不同参数的数组。
示例:
var thePromise = function(options) {
return new Promise(function(resolve, reject) {
// Some asynchronous code
resolve(value);
});
}
var parameters = [
{ a: 10, b: 15 },
{ a: 20, b: 30 }
];
我会把解析出来的value
求和到一个变量中,我们称它为total
。
这是我卡住的地方:
我需要 运行 只有当承诺的结果加到 total
低于定义的数量时,我才需要使用下一组参数来承诺承诺。
我尝试使用 async
.each()
,但这不起作用,因为在我调用 next()
函数之前调用了下一个承诺。
当前(无效)解决方案:
async.each(paramaters, function(options, next) {
thePromise(options).then(function(value) {
total += value;
if (total > 10) {
return next('limited');
}
next();
}).catch(next);
}, function(err) {
if (err && err !== 'limited) { // Handle error }
// Handle success
});
您需要使用 async.eachSeries,来自文档:
The same as each, only iterator is applied to each item in arr in series. The next iterator is only called once the current one has completed. This means the iterator functions will complete in order.
这样你就可以实现异步调用的同步迭代
这是我需要完成的:
我有一个函数(我们称之为 thePromise
),returns 一个承诺。
我有一个包含 运行 thePromise
的不同参数的数组。
示例:
var thePromise = function(options) {
return new Promise(function(resolve, reject) {
// Some asynchronous code
resolve(value);
});
}
var parameters = [
{ a: 10, b: 15 },
{ a: 20, b: 30 }
];
我会把解析出来的value
求和到一个变量中,我们称它为total
。
这是我卡住的地方:
我需要 运行 只有当承诺的结果加到 total
低于定义的数量时,我才需要使用下一组参数来承诺承诺。
我尝试使用 async
.each()
,但这不起作用,因为在我调用 next()
函数之前调用了下一个承诺。
当前(无效)解决方案:
async.each(paramaters, function(options, next) {
thePromise(options).then(function(value) {
total += value;
if (total > 10) {
return next('limited');
}
next();
}).catch(next);
}, function(err) {
if (err && err !== 'limited) { // Handle error }
// Handle success
});
您需要使用 async.eachSeries,来自文档:
The same as each, only iterator is applied to each item in arr in series. The next iterator is only called once the current one has completed. This means the iterator functions will complete in order.
这样你就可以实现异步调用的同步迭代