有一个 Nodejs 模块可以让你限制并发 Promise 的数量:
https://github.com/sindresorhus/p-queue
这是否使用多线程?
官方页面示例:
const {default: PQueue} = require('p-queue');
const got = require('got');
const queue = new PQueue({concurrency: os.cpus().length});
(async () => {
await queue.add(() => got('sindresorhus.com'));
console.log('Done: sindresorhus.com');
})();
(async () => {
await queue.add(() => got('ava.li'));
console.log('Done: ava.li');
})();
(async () => {
const task = await getUnicornTask();
await queue.add(task);
console.log('Done: Unicorn task');
})();
它会在不同的 cpu 线程中运行上面的每个异步函数吗?
最佳答案
Will it run each of the async functions above in different cpu threads?
不,当然不是。这不是异步函数的作用。它们所做的只是为顺序异步代码提供更好的语法。他们仍然normal promises带有 promise 回调,在 same single-threaded event loop as always 上运行。另请参阅Is promise.all useful given that javascript is executed in a single thread?
当然,got
包可以自由地使用nodejs的工作线程功能或其他东西来完成它的工作,它需要做的就是与await
很好地配合> 是返回一个 promise 。但这不会影响您的异步 IIFE 或调度函数的 p-queue
。
关于javascript - p-queue 使用多线程吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58894529/