sindresorhus / p-queue

Promise queue with concurrency control
MIT License
3.39k stars 182 forks source link

Default value for priority doesn't get applied #190

Open IboKhaled opened 1 year ago

IboKhaled commented 1 year ago

According to the documentation, when priority is left undefined, it should default to 0. However this doesn't seem to be the case. Instead, the promises seem to be executed in a random order (not the order they were inserted into the queue in!). When manually setting the priority to 0, the queue behaves as expected.

Example code:

import PQueue from "p-queue";

function delay(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

function addToQueue(name: string, priority?: number) {
  console.log(`adding ${name} to queue`);
  return queue.add(
    async () => {
      await delay(1000);
      console.log(`finished ${name}`);
      return Promise.resolve();
    },
    { priority }
  );
}

const queue = new PQueue({ concurrency: 1 });
const first = addToQueue("first");
const second = addToQueue("second");
const priority = addToQueue("priority", 1);
const third = addToQueue("third");
Example output Expected output
adding first to queue adding first to queue
adding second to queue adding second to queue
adding priority to queue adding priority to queue
adding third to queue adding third to queue
finished first finished first
finished third finished priority
finished priority finished second
finished second finished third