JS/TS

js的async和await

05-20 09:48

async/await 的介绍

async/await 是 ES8 引入的新语法,是 JavaScript 中用于简化异步操作的语法糖,用来简化 Promise 异步操作,它虽基于 Promise,但却让异步代码看起来更像同步代码,通过 async 声明和 await 修饰后,返回的不再是 Promise 实例,而是一个具体的值或数据对象,更容易理解和维护。

async:用于声明一个异步函数。

  • 异步函数会隐式返回一个 Promise 对象。
  • 如果函数返回值不是 Promise,它会被自动包装成 Promise.resolve(返回值)。

await:用于等待一个 Promise 的结果。

  • await 只能在 async 函数中使用。
  • 它会暂停当前 async 函数的执行,直到 Promise 完成(resolve 或 reject)。


入门案例

使用 async/await 简化 Promise 异步操作的实例代码如下:

//声明一个异步函数

async function main(){

//等待返回 Promise 结构

let r1 = await thenfs.readFile('./1.txt', 'utf8')

let r2 = await thenfs.readFile('./2.txt', 'utf8')

let r3 = await thenfs.readFile('./3.txt', 'utf8')

console.log(r1, r2, r3)

}


async/await 的使用注意事项

1、如果在 function中 使用了 await 关键字,则这个 function 前面必须被 async 修饰

async function 函数名() {

await ...

}

2、在 async 方法中,第一个 await 之前的代码会同步执行,await 之后的代码会异步执行


使用 async/await 通过 axios 发起请求

//发起 POST 请求

async request() {

try {

await axios.post("main", { id: 10 }, headers: {

'Content-Type': 'application/x-www-form-urlencoded'

})

.then( res => {

console.log(res)

})

.catch( error => {

console.log(error)

})

}

}

//发起 GET 请求

async request() {

try {

await axios.get("main", {

params: {

id: 10

}

})

.then( res => {

console.log(res)

})

.catch( error => {

console.log(error)

})

}

}



微信小程序
大潇博客 版权所有 Copyright ©2016~2026
京ICP备17004217号-6  合作QQ:284710375
天玺科技