在同步功能上正确执行异步功能

时间:2019-12-19 05:47:28

标签: node.js asynchronous promise synchronization

const mainTasks = ['mainTask1', 'mainTask2', 'mainTask3', 'mainTask4']
const subTasks = ['subTask1', 'subTask2', 'subTask3']
const defaultTimeout = 1000

// SubTasks should be run as async
// Tasks should be run as sync

const subTaskHandler = () => {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve();
        }, defaultTimeout * 2);
    })
}

const main = async () => {
    await Promise.all(
        mainTasks.map((mainTask, index) => {
            return new Promise(resolve => {
                setTimeout(async () => {
                    for (subTask of subTasks) {
                        await subTaskHandler(defaultTimeout)
                        console.log(`${mainTask} -> ${subTask}: Completed`)
                    }
                    resolve()
                }, defaultTimeout + index * 1000)
            })

        })
    )
    console.log('done')
}

main()

我将以同步方式执行 mainTasks ,并以异步方式执行 subTasks 最后,我尝试抓住 mainTasks 以及 subTasks 都完成的关键。 似乎我明白了,但我遇到了意外的结果。

mainTask1 -> subTask1: Completed
mainTask2 -> subTask1: Completed
mainTask3 -> subTask2: Completed
mainTask1 -> subTask2: Completed
mainTask4 -> subTask3: Completed
mainTask2 -> subTask2: Completed
mainTask3 -> subTask3: Completed
mainTask1 -> subTask3: Completed
mainTask4 -> subTask3: Completed
mainTask2 -> subTask3: Completed
mainTask3 -> subTask3: Completed
mainTask4 -> subTask3: Completed
done

mainTask4-> subTask1 和2在哪里?

1 个答案:

答案 0 :(得分:2)

与您

for (subTask of subTasks) {

您忘记声明subTask变量,因此它是隐式全局的-它没有块范围。在每个maintask的每次迭代上都将其重新分配。因此,在await内的异步for之后:

                for (subTask of subTasks) {
                    await subTaskHandler(defaultTimeout)
                    console.log(`${mainTask} -> ${subTask}: Completed`)
                }

await中的任何一个解析时,subTask变量将保存在最近初始化的子任务期间分配给它的值(而不是分配的变量)在当前子任务中添加到它。

更改为:

for (const subTask of subTasks) {

它会按预期工作。

const mainTasks = ['mainTask1', 'mainTask2', 'mainTask3', 'mainTask4']
const subTasks = ['subTask1', 'subTask2', 'subTask3']
const defaultTimeout = 1000

// SubTasks should be run as async
// Tasks should be run as sync

const subTaskHandler = () => {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve();
        }, defaultTimeout * 2);
    })
}

const main = async () => {
    await Promise.all(
        mainTasks.map((mainTask, index) => {
            return new Promise(resolve => {
                setTimeout(async () => {
                    for (const subTask of subTasks) {
                        await subTaskHandler(defaultTimeout)
                        console.log(`${mainTask} -> ${subTask}: Completed`)
                    }
                    resolve()
                }, defaultTimeout + index * 1000)
            })

        })
    )
    console.log('done')
}

main()

您还可以考虑使用严格模式和/或短绒,以尽早发现这些错误:

'use strict';

const mainTasks = ['mainTask1', 'mainTask2', 'mainTask3', 'mainTask4']
const subTasks = ['subTask1', 'subTask2', 'subTask3']
const defaultTimeout = 1000

// SubTasks should be run as async
// Tasks should be run as sync

const subTaskHandler = () => {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve();
        }, defaultTimeout * 2);
    })
}

const main = async () => {
    await Promise.all(
        mainTasks.map((mainTask, index) => {
            return new Promise(resolve => {
                setTimeout(async () => {
                    for (subTask of subTasks) {
                        await subTaskHandler(defaultTimeout)
                        console.log(`${mainTask} -> ${subTask}: Completed`)
                    }
                    resolve()
                }, defaultTimeout + index * 1000)
            })

        })
    )
    console.log('done')
}

main()

  

错误:未处理的承诺拒绝:ReferenceError:未定义subTask