search

Home  >  Q&A  >  body text

javascript - async/await and forEach issues

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']);
PHP中文网PHP中文网2752 days ago485

reply all(2)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-05-16 13:41:43

    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.

    let array = [0,1,2,3,4,5];
    (async ()=>{
      array.forEach(function(item){
        console.log(item);
        await wait(1000);//这是错误的写法
      });
    })();
    //因await只能用于 async 声明的函数上下文中, 故不能写在forEach内.下面我们来看正确的写法
    (async ()=>{
      for(let i=0,len=array.length;i<len;i++){
        console.log(array[i]);
        await wait(1000);
      }
    })();

    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.

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-16 13:41:43

    async When doing asynchronous loops it is best to use for ... of ... or Promise.all()

    reply
    0
  • Cancelreply