var a = [1, 2, 3];
var b = [3, 4, 5];
for (var i = 0; i < a.length; i++) {
console.log('value of i is ', i);
for (var j = 0; j < b.length; j++) {
console.log('value of j is ', j);
here some blocking code like setTimeout or any database call
}
}
我想要这个输出
value of i is ',0
value of j is ',0
value of j is ',1
value of j is ',2
value of i is ',1
value of j is ',0
value of j is ',1
value of j is ',2
答案 0 :(得分:1)
您可以使用async并等待它。 Async/Await正在兑现承诺:
var a = [1, 2, 3];
var b = [3, 4, 5];
async function asyncStuff(a, b) {
for (var i = 0; i < a.length; i++) {
console.log('value of i is ', i);
for (var j = 0; j < b.length; j++) {
console.log('value of j is ', j);
// Waits until the promise has resolved and continues the for-loop
await someDatabaseCall();
}
}
}
// Call your function
asyncStuff(a, b);
请注意,异步/等待不会阻止Array.forEach
的执行。