async和await是用来处理异步的。即你需要异步像同步一样执行,需要异步返回结果之后,再往下依据结果继续执行。
async 是“异步”的简写,而 await 可以认为是 async wait 的简写。
async 用于申明一个 function 是异步的,而 await 用于等待一个异步方法执行完成。
async function testAsync() {
return "hello async";
}
const result = testAsync();
console.log(result);
打印输出的是一个Promise 对象,async 函数会返回一个 Promise 对象。
在最外层不能用 await 获取其返回值的情况下,使用 then() 链来处理这个 Promise 对象。
当 async 函数没有返回值时,返回 Promise.resolve(undefined)
await
await只能放在async函数内部使用
await 用于一个异步操作之前,表明要“等待”这个异步操作的返回值。
await 也可以用于一个同步的值。
如果它等到的不是一个 Promise 对象,那 await 表达式的运算结果就是它等到的东西。
如果它等到的是一个 Promise 对象,await 就会阻塞后面的代码,等着 Promise 对象 resolve,然后得到 resolve 的值,作为 await 表达式的运算结果。
同步代码
const a = await 'hello world'
// 相当于
const a = await Promise.resolve('hello world');
// 所以直接写同步代码即可,不需要await关键字
const a = 'hello world';
异步代码
// 2s 之后返回双倍的值
function doubleAfter2seconds(num) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2 * num)
}, 2000);
})
}
async function testResult () {
let result = await doubleAfter2seconds(30);
console.log(result);
}
testResult();
// 2s 之后,输出了60.
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...



