javascript面试题:什么是 async/await 及其如何工作?
51. 什么是 async/await
及其如何工作?
async/await
是 JS 中编写异步或非阻塞代码的新方法。它建立在Promises之上,让异步代码的可读性和简洁度都更高。
async/await
是 JS 中编写异步或非阻塞代码的新方法。 它建立在Promises
之上,相对于 Promise 和回调,它的可读性和简洁度都更高。 但是,在使用此功能之前,我们必须先学习Promises
的基础知识,因为正如我之前所说,它是基于Promise
构建的,这意味着幕后使用仍然是Promise。
使用 Promise
function callApi() {
return fetch("url/to/api/endpoint")
.then(resp => resp.json())
.then(data => {
//do something with "data"
}).catch(err => {
//do something with "err"
});
}
复制代码
使用async/await
在async/await
,我们使用 tru/catch 语法来捕获异常。
async function callApi() {
try {
const resp = await fetch("url/to/api/endpoint");
const data = await resp.json();
//do something with "data"
} catch (e) {
//do something with "err"
}
}
复制代码
注意:使用 async
关键声明函数会隐式返回一个Promise。
const giveMeOne = async () => 1;
giveMeOne()
.then((num) => {
console.log(num); // logs 1
});
复制代码
注意:await
关键字只能在async function
中使用。在任何非async function的函数中使用await
关键字都会抛出错误。await
关键字在执行下一行代码之前等待右侧表达式(可能是一个Promise)返回。
const giveMeOne = async () => 1;
function getOne() {
try {
const num = await giveMeOne();
console.log(num);
} catch (e) {
console.log(e);
}
}
// Uncaught SyntaxError: await is only valid in async function
async function getTwo() {
try {
const num1 = await giveMeOne(); // 这行会等待右侧表达式执行完成
const num2 = await giveMeOne();
return num1 + num2;
} catch (e) {
console.log(e);
}
}
await getTwo(); // 2
作者:前端小智
链接:https://juejin.im/post/5e1faa3d51882520a167df0e
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
THE END