sindresorhus / p-limit

Run multiple promise-returning & async functions with limited concurrency
MIT License
1.84k stars 99 forks source link

how should i use clearqueue? #49

Closed WystanW closed 3 years ago

WystanW commented 3 years ago

I want to stop the pending tasks

sindresorhus commented 3 years ago

I don't understand the question. I think the docs are pretty clear about it.

WystanW commented 3 years ago

I don't understand the question. I think the docs are pretty clear about it.

I have an variable named 'switch' and a vue watcher to watch 'switch' ; if 'switch' is false,then I want to stop all the tasks pending in the limit queue.

watch: { switch: { handler(next, prev) { if (this.switch) { this.limit.clearQueue() } } }

but the tasks is still running to the end. The code cannot stop the tasks in the queue

sindresorhus commented 3 years ago

but the tasks is still running to the end.

You cannot stop the "active" tasks. .clearQueue() only clears the pending (yet to run) tasks. This is a limitation of promises. Once a promise starts, it cannot be stopped/canceled from the outside.

WystanW commented 3 years ago

but the tasks is still running to the end.

You cannot stop the "active" tasks. .clearQueue() only clears the pending (yet to run) tasks. This is a limitation of promises. Once a promise starts, it cannot be stopped/canceled from the outside.

Thanks for reply!!!

Yes! I just want to stop the pending tasks . As your example

const pLimit = require('p-limit');

const limit = pLimit(1);

const input = [
    limit(() => fetchSomething('foo')),
    limit(() => fetchSomething('bar')),
    limit(() => doSomething())
        // ......if there are 1000 functions
];

(async () => {
    // Only one promise is run at once
    const result = await Promise.all(input);
    console.log(result);
})();

if I have 1000 limit(() => myfunction()) then the code const result = await Promise.all(input); need time to finish.

In this period, may be there are 500 pending rasks, 1 running tasks, and 499 finished tasks. I just want to stop these 500 pending tasks when a variable called "switch" is true. But i don't know how to use limit.clearQueue()

if (this.switch) {
   this.limit.clearQueue() 
} 

Could U give me an example?

sindresorhus commented 3 years ago

You could do something like this:

const pLimit = require('p-limit');

const limit = pLimit(1);

const check = fn => {
    if (switch) {
       limit.clearQueue();
    }

    fn();
};

const input = [
    limit(check(() => fetchSomething('foo'))),
    limit(check(() => fetchSomething('bar'))),
    limit(check(() => doSomething()))
        // ......if there are 1000 functions
];

(async () => {
    // Only one promise is run at once
    const result = await Promise.all(input);
    console.log(result);
})();