一震嫉、async函數(shù)
An async function is a function declared with the async keyword
- 函數(shù)名之前加上async關(guān)鍵字,就表明該函數(shù)內(nèi)部有異步操作
- async 函數(shù)返回一個 Promise對象(JS - Promise使用)
1.1 async函數(shù)返回值
可用async函數(shù)返回值特性重構(gòu)
function foo() {
return new Promise((resolve) => {
resolve("success")
})
}
async function bar(){
return "success"
}
foo().then((res) => {
res // success
})
bar().then((res) => {
res // success
})
捕獲失敗拋出異常即可
async function foo(){
if(異步請求成功){
return 'success'
}else{
throw 'error'
}
}
foo().then((res) => {
res // success
}).catch(err=>{
err // error
})
二姥饰、await 操作符
The await operator is used to wait for a Promise. It can only be used inside an async function.
- await 操作符用于等待一個Promise 對象骂际。
- 只能在異步函數(shù) async function 中使用速兔。
2.1 await 用法
- await 遇到Promis時會暫停async function 的執(zhí)行价淌,等待 Promise 處理完成。
- 若 Promise 正常處理(fulfilled)啦鸣,其回調(diào)的resolve函數(shù)參數(shù)作為 await 表達式的值薛耻,繼續(xù)執(zhí)行 async function。
- 若 Promise 處理異常(rejected)赏陵,await 表達式會把 Promise 的異常原因拋出饼齿。
- 如果 await 操作符后的表達式的值不是一個 Promise,則返回該值本身蝙搔。
2.1.1 遇到Promise暫停async 函數(shù)
async function foo() {
await new Promise((resolve, reject) => {
setTimeout(resolve,2000)
})
console.log('2s后執(zhí)行');
}
foo()
2.1.2 Promise resolve的值作為await的返回值
async function foo() {
var why = await Promise.resolve("success")
why // success
}
foo()
2.1.3 await 拋出 Promise 處理異常
async function foo() {
try {
await Promise.reject("error")
// Uncaught (in promise) error
} catch (err) {
err // error
}
}
foo()
2.1.4 非Promise對象直接返回對應的值缕溉。
async function foo() {
var bar= await 'why'
bar // why
}
foo()
2.2 await結(jié)合Node.js簡單應用
const fs = require("fs")
type IRead = (path: string) => void
type IWrite = (path: string, content: string, flag: string) => void
const readFile: IRead = (path) => {
return new Promise((resolve) => {
fs.readFile(path, { encoding: "utf-8" }, (err, data) => {
if (!err) resolve(data)
})
})
}
const writeFile: IWrite = (path, content, flag) => {
return new Promise((resolve) => {
fs.writeFile(path, content, { flag, encoding: "utf-8" }, (err) => {
if (!err) resolve()
})
})
}
fs.readdir("../NODE", (err, files) => {
if (err) return
files.forEach(async (item) => {
let content = await readFile(item)
await writeFile("integration.text", content as any as string,"a+")
console.log("Write succeeded")
})
})
將讀寫文件封裝為返回Promise函數(shù),用await關(guān)鍵字,等待文件的讀取回調(diào)成功以后,再將文件寫入集合.