回调函数在for循环中,回调的顺序就会不确定,不按顺序。以下方法能使其同步执行:
一、使用 async 和 await
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
(async function loop() {
for (let i = 0; i < 10; i++) {
await delay(Math.random() * 1000);
console.log(i);
}
})();
二、使用 Promise
let p = Promise.resolve();
for (let i = 0; i < 10; i++) {
p = p.then(_ => new Promise(resolve =>
setTimeout(function () {
console.log(i);
resolve();
}, 1000)
));
}