62 javascript asynchronous node.js async-await
我正在使用该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.
});
});
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我无法将该myFunction
函数声明为异步,因为我无法访问eachLimit
函数的第二个回调内的值.
jib*_*jib 49
你在promise构造函数执行器函数中有效地使用了promise,所以这就是Promise构造函数的反模式.
您的代码是主要风险的一个很好的例子:不安全地传播所有错误.读那里的原因.
此外,使用async
/ await
可以使相同的陷阱更令人惊讶.相比:
let p = new Promise(resolve => {
""(); // TypeError
resolve();
});
(async () => {
await p;
})().catch(e => console.log("Caught: " + e)); // Catches it.
Run Code Online (Sandbox Code Playgroud)
与天真(错误)async
等价物:
let p = new Promise(async resolve => {
""(); // TypeError
resolve();
});
(async () => {
await p;
})().catch(e => console.log("Caught: " + e)); // Doesn't catch it!
Run Code Online (Sandbox Code Playgroud)
在浏览器的Web控制台中查找最后一个.
第一个是有效的,因为Promise构造函数执行函数中的任何直接异常都会方便地拒绝新构造的promise(但.then
在你自己的内部).
第二个不起作用,因为async
函数中的任何立即异常都会拒绝函数本身返回async
的隐式promise.
由于promise构造函数执行函数的返回值未使用,这是个坏消息!
没有理由你不能定义myFunction
为async
:
async function myFunction() {
let array = await getAsyncArray();
return new Promise((resolve, reject) => {
eachLimit(array, 500, (item, callback) => {
// do other things that use native promises.
}, error => {
if (error) return reject(error);
// resolve here passing the next value.
});
});
}
Run Code Online (Sandbox Code Playgroud)
虽然为什么使用过时的并发控制库await
?
Vla*_*tko 34
我同意上面给出的答案,但有时在你的承诺中使用异步会更简洁,特别是如果你想链接几个返回承诺的操作并避免then().then()
地狱。我会考虑在那种情况下使用这样的东西:
const operation1 = Promise.resolve(5)
const operation2 = Promise.resolve(15)
const publishResult = () => Promise.reject(`Can't publish`)
let p = new Promise((resolve, reject) => {
(async () => {
try {
const op1 = await operation1;
const op2 = await operation2;
if (op2 == null) {
throw new Error('Validation error');
}
const res = op1 + op2;
const result = await publishResult(res);
resolve(result)
} catch (err) {
reject(err)
}
})()
});
(async () => {
await p;
})().catch(e => console.log("Caught: " + e));
Run Code Online (Sandbox Code Playgroud)
Promise
构造函数的函数不是异步的,因此 linter 不会显示错误。await
.但是有一个缺点是您必须记住try/catch
将其放置并附加到reject
.
相信反模式就是反模式
异步 Promise 回调中的抛出很容易被捕获。
(async () => {
try {
await new Promise (async (FULFILL, BREAK) => {
try {
throw null;
}
catch (BALL) {
BREAK (BALL);
}
});
}
catch (BALL) {
console.log ("(A) BALL CAUGHT", BALL);
throw BALL;
}
}) ().
catch (BALL => {
console.log ("(B) BALL CAUGHT", BALL);
});
Run Code Online (Sandbox Code Playgroud)
或者更简单地说,
(async () => {
await new Promise (async (FULFILL, BREAK) => {
try {
throw null;
}
catch (BALL) {
BREAK (BALL);
}
});
}) ().
catch (BALL => {
console.log ("(B) BALL CAUGHT", BALL);
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
33982 次 |
最近记录: |