什么是async,什么是await,async和await的区别,async和await的理解

 ES6 作为多年来 JavaScript 的重大版本变革,受到 JavaScript 开发者们的普遍欢迎,也正是从 ES6 (ES2015) 开始,JavaScript 版本发布变为年更,即每年发布一个新版本,以年号标识版本

随着async/await正式纳入ES7标准,据说是异步编程终级解决方案的 async/await。

async 是“异步”的意思,而 await 是等待的意思,await 用于等待一个异步任务执行完成的结果。

async/await 是一种编写异步代码的新方法(以前是采用回调和 promise)。
async/await 是建立在 promise 的基础上。
async/await 像 promise 一样,也是非阻塞的。
async/await 让异步代码看起来、表现起来更像同步代码。
一、Async
1、async

async修饰的函数就是异步函数,该函数的返回值是promise对象。

async function f1(){

    return "hello f1";

}

var t = f1();

console.log(t);// promise对象。

f1().then(function(str){

    console.log("str:"+str); //str:hello f1

});

2、async和promise的对比

async function f1(){

    return "hello f1";

}

function f2(){

    return new Promise((resolve, reject) => {

        resolve('hello f2');

    })

}

f1().then(function(str){

    console.log("str:"+str);

});

f2().then(function(str){

    console.log("str:"+str);

});

从以上代码可以看到,执行结果一样。Asnyc修饰的函数的返回值会作为resolve对应函数的参数。

二、await
    首先,await只能写在async修饰的函数里。Await是等待的意思,await修饰的代码会等待。在函数里,碰到await修饰的代码时,await朝后的代码都会等待。

async function f1() {

    console.log("f1开始");

    const data = await "hello await"; //await后面的代码停止。

    console.log("--------终于等到其它代码执行完毕----------");     

    console.log(data);                                

    return data;

}

f1().then(function(str){

    console.log("str:"+str);

});

console.log("外部的");

执行结果:

三、面试题:
async,await,promise,setTimeout的执行顺序

setTimeout(function(){

    console.log(1);

},1000);

setTimeout(function(){

    console.log(2);

},0);

// Promise.resolve(console.log(3)).then(()=>{

//     console.log(4);

// });

new Promise(function(resolve,reject){

    console.log(3);

    resolve();

}).then(()=>{

    console.log(4);

});

async function async1(){

    console.log(5);

    await async2();

    console.log(6);

}

async function async2(){

    console.log(7);

}

async1();

console.log(8);

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值