fangchaolong
文章57
标签24
分类10
es6 async和await的区别

es6 async和await的区别

async和await从字面上表示,异步和同步,本文主要讲解它们的特性

await (同步)

await 只能在async函数内部使用,不能再顶级作用域使用
await 只能作用于返回值是promise的函数
await 可以让JavaScript进行等待,直到一个promise执行并返回它的结果,JavaScript才会继续往下执行。

举例:


var abc = function() {
    return new Promise((resolve,reject) => {
        setTimeout(() => {
            console.log('同步和异步')
            resolve()
        },0)

    })
}

await abc()
console.log('1111')
console.log('2222')
// 同步和异步
// 1111
// 2222

async 异步

async 确保函数返回一个promise


  console.log(1);
  async function f () {
    console.log(2)
    return 'hello world!'
  }
  f().then(result=>{
    console.log(result);
  })
  console.log(3);
  //1,2,3,'hello,world'

无以生计,卖文苟延

微信
支付宝