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

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

 

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

 

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

  1. async/await 是一种编写异步代码的新方法(以前是采用回调和 promise)。
  2. async/await 是建立在 promise 的基础上。
  3. async/await 像 promise 一样,也是非阻塞的。
  4. 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);

 

 

发布了219 篇原创文章 · 获赞 347 · 访问量 34万+

猜你喜欢

转载自blog.csdn.net/jiang7701037/article/details/103148245