作用: 是一套关于异步的解决方案
await有两个作用,一是作为求值关键字,二是将异步操作变成同步操作;如果方法中使用了await,那么在方法前面必须加上async
当await作为求值关键字时 后面可以跟Promise或表达式,可以直接获取Promise中的值或表达式的值
跟Promise
app.use(async (ctx, next) => {
// next()返回的是Promise,a的值是"hello, world!"
const a = await next();
const b = next();
b.then((res) => {
console.log(res); // 打印出"hello, world!"
})
});
app.use((ctx, next) => {
return "hello, world!";
})
跟表达式
const a = await 100*100;
async的作用是将方法的返回值封装成Promise
async function t() {
return "hello";
}
console.log(t()); // 打印出 Promise{"hello"}