ES6 async await 面试题


转自:https://juejin.im/post/5c0397186fb9a049b5068e54

1、题目一

async function async1(){ console.log('async1 start') await async2() console.log('async1 end') } async function async2(){ console.log('async2') } console.log('script start') setTimeout(function(){ console.log('setTimeout') },0) async1(); new Promise(function(resolve){ console.log('promise1') resolve(); }).then(function(){ console.log('promise2') }) console.log('script end')

2、题目二:

async function async1(){ console.log('async1 start') await async2() console.log('async1 end') } function async2(){ // 去掉了 async 关键字
    console.log('async2'); } console.log('script start') setTimeout(function(){ console.log('setTimeout') },0) async1(); new Promise(function(resolve){ console.log('promise1') resolve(); }).then(function(){ console.log('promise2') }) console.log('script end')

需要说明的是:

正常情况下,await命令后面是一个 Promise 对象,返回该对象的结果。如果不是 Promise 对象,就直接返回对应的值(相当于直接Promise.resolve)

例子:

async function f() { // 等同于
  // return 123;
  return await 123; } f().then(v => console.log(v)) // 123

上面代码中,await命令的参数是数值123,这时等同于return 123


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM