ES7之async/await

async/await是写异步代码的新方式,基于Promise实现的,在语法上更加简洁。

Async/Await基本规则
  • async 表示这是一个async函数,await只能用在这个函数里面。
  • await 表示在这里等待promise返回结果了,再继续执行。
  • await 后面跟着的应该是一个promise对象(当然其他返回值也可以,只不过会立即执行,就没有意义了)
例子
let syncPrint = async (text)=>{
    await setTimeout(()=>{
        console.log(`Hello ${text}`);
    },1000);
}

syncPrint('Js')
syncPrint('ES7')
console.log('============================')
与promise相比代码简洁了
//promise
let promise = (text)=>{
    return new Promise((resolve)=>{
        resolve(`------------- ${text}`)
    });
}
promise("python").then(result=> {
    console.log(`============= ${result}`);
});

//async/await
let async = async (text)=>{
    let result = await `------------- ${text}`;
    await console.log(`============= ${result}`)
}
async('c++');

猜你喜欢

转载自blog.csdn.net/summerpowerz/article/details/80467436