什么是 `async/await` 及其如何工作?
async/await
是 JS 中编写异步或非阻塞代码的新方法。它建立在Promise之上,让异步代码的可读性和简洁度都更高。
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
,我们使用 try/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
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » 什么是 `async/await` 及其如何工作?
码云笔记 » 什么是 `async/await` 及其如何工作?