在新的Promise()构造函数中使用asynchronous/等待的反模式?
我使用async.eachLimit
函数来一次控制最大操作数。
const { eachLimit } = require("async"); function myFunction() { return new Promise(async (resolve, reject) => { eachLimit((await getAsyncArray), 500, (item, callback) => { // do other things that use native promises. }, (error) => { if (error) return reject(error); // resolve here passing the next value. }); }); }
正如你所看到的,我不能将myFunction
函数声明为async,因为我不能访问eachLimit
函数的第二个callback函数中的值。
您在promise构造函数的执行函数内部有效地使用promise,所以这是Promise构造函数的反模式 。
你的代码是主要风险的一个很好的例子:不能安全地传播所有的错误。 阅读为什么那里 。
另外,使用async
/ await
可以使相同的陷阱更令人惊讶。 比较:
let p = new Promise(resolve => { ""(); // TypeError resolve(); }); (async () => { await p; })().catch(e => console.log("Caught: " + e)); // Catches it.