Home > Software design >  Why does the for of loop inside of an async function break instead of awaiting?
Why does the for of loop inside of an async function break instead of awaiting?

Time:11-13

Edit 2: So I changed things to use setTimeOut instead and that did the trick. See the accepted answer for what was causing the actual error. The code below works fine.

async function getSlices() {
    const imgBuffs = await sliceImg('./example.png', 128, 128)
    let saveInd = 0
    for (const buff of imgBuffs) {
        const asciified = await asciify(buff, options)
        console.log(asciified)
        await setTimeout(() => {}, 1000)
        await execShellCommand(`clear | import -window root -crop 904x904 0 66 ${saveInd}.png`).then((res, rej) => saveInd  )
        await setTimeout(() => {}, 1000)
    }

}

Edit: Added missing important code

The following function slices images and turns them into ascii (this works). Then, the function is supposed to console.log the data, wait a little, take a screenshot, wait again and then move on to the next saved buffer. Without delays, the function works, but it takes badly timed screenshots. With the await delays, the function stops at the first delay.

async function getSlices() {
    const imgBuffs = await sliceImg('./example.png', 128, 128)
    for (const buff of imgBuffs) {
        console.log('Starting to wait for asciified')
        const asciified = await asciify(buff, options)
        console.log(asciified)
        console.log('Ascifiied done, waiting for first delay')
// the function stops here...
        await delay(100)
        console.log('executing the command')
        await execShellCommand('clear | import -window root -crop 904x904 0 66  Image2.png').then((res, rej) => console.log('Shot saved'))
        await delay(100)
        console.log('all done')
}

async function execShellCommand(cmd) {
    const exec = require('child_process').exec;
    return new Promise((resolve, reject) => {
        exec(cmd, (error, stdout, stderr) => {
            if (error) {
                console.log(error);
            }
            console.log('here')
            resolve(stdout ? stdout : stderr);
        });
    });
}

const delay = ms => new Promise(res => setTimeout(res, ms));

CodePudding user response:

You probably get

Cannot access 'delay' before initialization

You don't have any catch or try..catch blocks so you don't see the error

Invisible error:

async function getSlices() {
  console.log('Starting to wait for asciified')
  await delay(100)
  console.log('all done')
}

getSlices()

const delay = ms => new Promise(res => setTimeout(res, ms));

Visible with catch:

async function getSlices() {
  console.log('Starting to wait for asciified')
  await delay(100)
  console.log('all done')
}

getSlices().catch(console.error)

const delay = ms => new Promise(res => setTimeout(res, ms));

  • Related