Method 1: No problem
(async function () {
for (let i = 0; i < triggerArr.length; ++i) {
await sleep();
triggerArr[i]();
}
})();
Method 2: They are output together, why? (No waiting)
const test = async function (item) {
await sleep();
item();
};
triggerArr.forEach(test);
All codes
function signalLamp(singalArr) {
function tic(sign, delay) {
return () => new Promise((res, rej) => {
setTimeout(() => {
res();
console.log(sign);
}, delay || 1000);
});
}
const rawArr = singalArr.slice();
const triggerArr = rawArr.reduce(function (prev, item) {
return prev.concat([tic(item, 1000)]);
}, []);
const sleep = () => new Promise((res, rej) => setTimeout(res, 1000));
/* Method 1 */
(async function () {
for (let i = 0; i < triggerArr.length; ++i) {
await sleep();
triggerArr[i]();
}
})();
/* Method 2 */
// const test = async function (item) {
// await sleep();
// item();
// };
// triggerArr.forEach(test);
}
signalLamp(['red', 'green', 'yellow']);
Let me tell you.
await can only be used in the function context of async declaration. As shown below, in forEach, await cannot be used directly.
Looking carefully, I found that your problem is another situation.
If you pass test as a callback function, the sleep method is executed synchronously, and await is still effective, but at the same time. Therefore, subsequent functions will be executed together after waiting for the same time.
async When doing asynchronous loops it is best to use for ... of ... or Promise.all()