笔记
What is Async/Await?
Async/Await基于Promise, 并可以很好的与基于Promise的APIs协同工作
Async - 声明一个异步方法 (async function someName(){...}).
- 将一个普通函数转换为一个Promise
- 调用async函数式, 无论函数体返回任何值, 都会用resolve进行处理
- Async函数启用await
Await - 暂停执行async 函数 (var result = await someAsyncCall();).
- 将await置于Promise调用之前, 会暂停执行之后的代码, 直到Promise执行完成并返回结果后才能恢复
- Await只能搭配Promise一起使用, 而不能与callbacks配合使用
- Await只能用于async函数内
以下为Promises和Async/Await实现方式:
// Promise 实现方式
function getJSON(){
// To make the function blocking we manually create a Promise.
return new Promise( function(resolve) {
axios.get('https://tutorialzine.com/misc/files/example.json')
.then( function(json) {
// The data from the request is available in a .then block
// We return the result using resolve.
resolve(json);
});
});
}
// Async/Await 实现方式
// The async keyword will automatically create a new Promise and return it.
async function getJSONAsync(){
// The await keyword saves us from having to write a .then() block.
let json = await axios.get('https://tutorialzine.com/misc/files/example.json');
// The result of the GET request is available in the json variable.
// We return it just like in a regular synchronous function.
return json;
}
两者都返回Promises, 并用resolve处理axios返回的JSON 数据, 于是, 我们可以这样调用async函数:
getJSONAsync().then( function(result) {
// Do something with result.
});
Async/Await错误处理
在函数内部使用try/catch捕获:
async function doSomethingAsync(){
try {
// This async call may fail.
let result = await someAsyncCall();
}
catch(error) {
// If it does we will catch the error here.
}
}
根据具体场景的需要, 我们也可以在函数外捕获.由于所有的async函数返回的都是Promises, 我们可以简单的通过.catch()
进行捕获
// Async function without a try/catch block.
async function doSomethingAsync(){
// This async call may fail.
let result = await someAsyncCall();
return result;
}
// We catch the error upon calling the function.
doSomethingAsync().
.then(successHandler)
.catch(errorHandler);
注意, 慎重选择容错处理方式, 同事使用try/catch
,catch()
很可能出现问题
Async 函数要点
通過 async function 定議的 function/Object 就是一個回傳AsyncFunction
的 Object。使用 async 處理非同步的 Promise function,回傳的值其實是 Resolve 的值;相似的, async exception 的結果和 Promise Reject 的結果也是一模一樣(Mozilla)。
async function asyncSleep (para){
return await sleep(para)
}
var result = await asyncSleep(2)
//result is 4
asyncSleep(3).then(function(result2){
//result2 is 9
})
资料
JavaScript Async/Await Explained in 10 Minutes