等待异步队列继续处理(异步模块)

时间:2018-09-28 15:14:15

标签: javascript asynchronous async-await queue async.js

我正在尝试使用Node.js和异步模块构建队列,但是无法正常工作。

这是我的代码:

const async = require('async');

const queueSize = 10;
const taskHandler = function (task, done) {
    task(done);
};

const myQueue = async.queue(taskHandler, queueSize);

myQueue.drain = function () {
    console.log('The queue is now empty.');
};

function delay() {
    return new Promise(resolve => setTimeout(resolve, 1000));
}

async function delayedLog(item) {
    await delay();
    console.log(item);
}

const run = async () => {
    for (let item = 0; item < 30; item++) {
        myQueue.push(async function (done) {
            await delayedLog(item)
            done();
        });
    }
}

(async () => {
    console.log('START');
    await run();
    console.log('END);
})()

我想要什么:

START
// logs from delayedLog
END 

输出:

START
END 
// logs from delayedLog

如您所见,等待不起作用。我试图使模块分散,但问题仍然存在。我尝试使用d3队列,但遇到了完全相同的问题。

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

您的程序按原样工作。实际上,您不需要为函数async声明run()。此功能仅是将30个异步任务放入队列中以供以后执行,然后在此之后结束。

我不清楚您想要什么,但是如果您想执行console.log('END')逻辑,则仅完成队列中的每个异步任务。请将其移至队列的drain()函数。

答案 1 :(得分:0)

As @Chiến Nghê said you are using some async/await where there is no need to but this is another problem.

Your await isn't working at the end because your drain function is called at the end of your queue and it's not returning a promise.

You have to promisify your function, here is a sample example to do that:

function end() {
    return new Promise((resolve, reject) => {
        myQueue.drain = function () {
            console.log('The queue is now empty.');
            resolve();
        };
    })
}

And then you can use your async await on your end function:

(async () => {
    console.log('START');
    run();
    await end();
    console.log('END');
})()

Output:

START
// a lot of logs
END