Async/Await 具有易于理解的示例。
我们首先来了解一下Async关键字。
将此关键字放在返回承诺或执行异步任务的函数之前。
const foo = async () => {
return 'done';
}
foo().then((res) => console.log(res));
// done
如果您认为您的函数将异步运行(从 API 获取数据),那么请在该函数之前使用 async 关键字。
现在有另一个关键字Await,它仅在异步函数内有效。
(有一个顶级 await 的概念,其中 await 关键字可以在异步函数之外使用。)
Await 关键字的简单含义是让 JavaScript 等待直到任务完成。
const asyncTask = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('done');
}, 1000);
});
}
const foo = async () => {
const res = await asyncTask();
console.log(res);
}
console.log('Before Foo Call');
foo();
console.log('After Foo Call');
在上面的例子中,我创建了一个虚拟函数,它需要一秒钟才能返回其结果。
还有另一个函数 foo 调用 asyncTask(带有 await 关键字)并打印结果。
我放了两个日志,一个是在调用 foo 之前,另一个是在调用 foo 之后。
你觉得输出会是什么?🤔
您可能知道,每当 JavaScript 遇到 await 关键字时,它都会停止当前函数的执行并将其放入回调队列并开始执行下一个语句,即第二个控制台日志。
这是上述代码的输出。
Before Foo Call
After Foo Call
done
使用 async/await 时处理错误
在上面的例子中,我们的承诺正常解决,并且我们在控制台上打印结果。
但如果被拒绝,它将引发错误,因此我们应该在处理承诺时处理错误。
使用 try/catch 块。
const asyncTask = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject('Something not working!');
}, 1000);
});
}
const foo = async () => {
try {
const res = await asyncTask();
console.log(res);
} catch (err) {
console.log(err);
}
console.log('After calling AsyncTask');
}
foo();
现在,如果我们的 asyncTask 函数抛出错误,控制将进入 catch 块并简单地打印错误消息,然后它将开始执行下一个语句。
输出
Something not working!
After calling AsyncTask
很干净。不是吗?
现在,尝试在下一个项目中使用 async/await 而不是 then/catch。
如果您喜欢这篇文章,请点赞、分享并标记🔖这篇文章!
🏃♂️ 你可以关注我 👇
🕊 推特:https://twitter.com/nehal_mahida
👨💻 Github:https://github.com/NehalMahida