ES7 Async Await语法

koa异步处理Async、Await、promise的使用

  • async声明 一个函数function是异步的,将目标方法变成异步操作。注意async函数返回的是一个promise对象。
  • await等待一个异步方法执行完成。将异步执行阻塞为同步执行。

声明async函数

async function add() {
    return 'this is async'
}
console.log(add());
//Promise { 'this is async' }
//返回一个promise对象

获取异步函数的返回值

//方法一
let data = async function add() {
    return 'this is async'
}
data().then(function (data) {
    console.log(data);
    
})
//this is async
//方法二
async function getDdata() {
    console.log(2);
    return 'this is data'
}
async function test() {
    console.log(1);
    let d = await getDdata();
    console.log(d);
    console.log(3);  
}
test()
//1
//2
//this is data
//3

 

你可能感兴趣的:(ES6)