await与async的作用及用法
await与async的作用及用法
async和await被称作是异步的终极解决方案
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;
-
-
将异步操作变成同步操作
await可以阻塞当前线程,将异步操作变成同步,被阻塞的线程并没有被空闲,而是去执行其他的操作
async的作用是将方法的返回值封装成Promise
async function t() {
return "hello";
}
console.log(t()); // 打印出 Promise{"hello"}