You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 08:10:46