Node.js 使用 Promise解释异步等待
现代 JavaScript 带来了异步等待功能,使开发人员能够以看起来和感觉像同步的方式编写异步代码。这有助于消除 Promise 嵌套所带来的许多问题,并且还可以使异步代码更易于阅读和编写。
要使用异步等待,我们只需要创建一个包含 try-catch 块的异步函数。在 try 块中,我们将等待 Promise 的完成。如果它被解析,我们将得到结果,否则将通过 catch 块抛出错误。等待只能在异步函数、异步回调或异步箭头函数内部使用。
示例:
const mod = (a, b) => {
return new Promise((resolve, reject) => {
if (b == 0) {
// Rejected (error)
reject("Modulo zero is not allowed");
} else {
// Resolved (Success)
resolve(a % b);
}
});
};
// 5 mod 2 will give result 1
async function _5mod2() {
try {
const res = await mod(5, 2);
console.log(`The result of division is {res}`);
} catch (err) {
console.log(err);
}
};
_5mod2();
// 5 mod 0 will give error
async function _5mod0() {
try {
const res = await mod(5, 0);
console.log(`The result of division is{res}`);
} catch (err) {
console.log(err);
}
};
_5mod0();
输出:
The result of division is 1
Modulo zero is not allowed