async函数中的for of循环为何未等待就中断?
问题:添加await延迟后async函数在第一个延迟处停止执行
以下函数用于将图片切片并转换为ASCII格式(这部分功能正常)。预期执行流程为:打印转换后的数据、短暂等待、截取屏幕截图、再次等待,然后处理下一个缓存的图片数据。不添加延迟时函数可运行,但截图时机不准确;添加await延迟后,函数在第一个延迟处就停止执行。
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));
编辑:补充了缺失的关键代码
编辑2:我改为使用setTimeout后问题解决了。实际错误原因可查看已采纳的答案。以下代码运行正常。
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) } }
内容的提问来源于stack exchange,提问作者VictoriaStudios
相关产品推荐
相关产品推荐

