jessetane / queue

Asynchronous function queue with adjustable concurrency
MIT License
764 stars 66 forks source link

jobs do not wait for previous async jobs to finish #78

Closed slaurent22 closed 3 years ago

slaurent22 commented 3 years ago

In the following example, the job returning "a" is queued first, so I would expect it to complete prior to starting the job for "b". However, the job for "b" is triggered before the job for "a" finishes

const q = new Queue({ results: [], });
q.on("end", () => {
    console.log("ended: ", q.results);
}).on("success", (result: unknown) => {
    console.log("success:", result);
});

q.push(() => new Promise<string>(resolve => {
    console.log("processing a");
    setTimeout(() => {
        console.log("resolving a");
        resolve("a");
    }, 200);
}));
q.push(() => {
    console.log("resolving b");
    return Promise.resolve("b");
});

q.start();

Observed Result

processing a
resolving b
success: b
resolving a
success: a
ended:  [ [ 'a' ], [ 'b' ] ]

I could submit a pull request with a simple change at https://github.com/jessetane/queue/blob/e15babc6f54f20ad622ec1756d0f9a59d6d03164/index.js#L154 to have that read else if. That way, the next job only starts if the previous job is not awaited.

jessetane commented 3 years ago

use q.concurrency = 1 if you want jobs to run in series

slaurent22 commented 3 years ago

Thank you!