在给定的示例中,如何让 for
循环等待回调函数完成?
function callAPI(callback) {
setTimeout(function () {
console.log('waited until the API response came!');
callback(true);
}, 3000);
}
for (var i = 0; i < 3; i++) {
console.log('i:', i);
callAPI(function(response) {
console.log('response is:', response);
//i++; //tried to move the loop index here!
});
}