在 for 循环内等待直到回调完成

时间:2021-03-19 10:38:05

标签: javascript loops asynchronous

在给定的示例中,如何让 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!
    });
}

0 个答案:

没有答案
相关问题