我正在尝试在for
循环中编写一个函数。但是循环不会等到获得内部函数的响应。如何在每次获得函数响应之前停止循环?
在此过程中,下一个循环取决于函数的响应。
我的示例代码:
var a = function(data, callback) {
var d = 1;
for (var i = 0; i < data.length; i++) {
b(d, function(err, result) {
if (!err) {
d = result;
}
if ((i + 1) === data.length) {
callback(err, 'something');
}
});
}
}
var b = function(data, callback) {
var c = data + 1;
callback(null, c);
}
在此代码中,for
循环不会等到它从函数b
获得响应。
答案 0 :(得分:6)
您可以通过在回调中调用递归函数调用来轻松迭代输入数组:
'use strict';
const a = function(data, callback) {
let i = 0;
let sum = 0;
// loop function
function next() {
const x = data[i++];
if (!x) {
return callback(null, sum);
}
return b(x, (err, data) => {
sum += data;
next();
});
}
next(); // starts iterating
}
// multiplies data * 3
const b = function(data, callback) {
let c = data * 3;
callback(null, c);
}
a([1, 2, 3], (err, data) => {
console.log(data); // prints 18
});
答案 1 :(得分:4)
您可以轻松地重构代码以使用Promise
s:
function a (data) {
let promise = Promise.resolve(1);
for (let i = 0; i < data.length; i++) {
promise = promise.then(b);
}
return promise.then(function (v) {
// v is the value computed by the promise chain
return 'something';
});
}
function b (data) {
// some async action that returns a promise
return Promise.resolve(data + 1);
}
用法:
a(['a', 'b', 'c']).then(result => console.log(result)); // logs 'something'
使用promises可以使用async function s:
处理异步代码,如同步代码async function a (data) {
let v = 1;
for (let i = 0; i < data.length; i++) {
// looks like synchronous code, but is asynchronous
v = await b(v);
}
// v is the value computed by the asynchronous loop
return 'something';
}