ES7之async、await

先久闻async、await,今日终于天时、地利、人和来一睹芳容。

先来看一列

代码片段:

async function test() {
  const response = await new Promise(resolve => {
     setTimeout(() => {
         resolve("test");
      }, 1000);
  });
  console.log(response);
}
test();

输出结果:

test

疑问:response居然拿到了promise的resolve返回值"test"?

对比例子一:

代码片段:

function test() {
  const response = new Promise(resolve => {
   setTimeout(() => {
       resolve("test");
    }, 1000);
  });
  console.log(response);
}
test();

输出结果:

Promise {<pending>}

结果分析:new Promise返回Promise对象赋值于response,既然如此为何文章开始列子使用async、await便可拿到promise对象的resolve返回值?那当然是因为…我也不知道,以后知道了再补充。

对比例子二:

代码片段:

async function test() {
  console.time('asyncStart')
  const response = await new Promise(resolve => {
      setTimeout(() => {
          resolve("test");
      }, 1000);
  });
  console.timeEnd('asyncStart')
  console.log(response);
}
test();

输出结果:

asyncStart: 1000.716064453125ms
test

结果分析:await new Promise…代码片段执行时长将近一秒,极像const response = “test”。亦由此可知async、await为何像同步写法。

传闻koa使用async、await解决了express回调地狱,既然如此咱们便比较比较。

代码片段:

//回调
function start(a,cb){
  new Promise(resolve=>{
    setTimeout(()=>{
      resolve(a)
    },1000)
  })
  .then((result)=>{
    new Promise(resolve=>{
      setTimeout(()=>{
        resolve(result)
      },1000)
    })
    .then((res)=>{
      cb(res);
    })
  })
}
start(1,function(res){console.log(res)})

// async、await
async function test(b,cb){
  var result = await new Promise(resolve=>{
    setTimeout(()=>{
      resolve(b)
    },1000)
  })
  var res = await new Promise(resolve=>{
    setTimeout(()=>{
      resolve(result)
    },1000)
  })
  cb(res)
}
test(2,function(res){console.log(res)})

输出结果:

1
2

结果分析:不用多说,自己感受,这仅仅是两层而已。
再来感受一段有意思的
代码片段:

async function test(str) {
    return await new Promise(resolve => {
        setTimeout(() => {
            resolve(str)
        }, 1000);
    })
}

async function a(){
    console.time('a')
    console.log(await test('a--str1'));
    console.log(await test('a--str2'));
    console.timeEnd('a')
}
a();

async function b(){
    console.time('b')
    var b1 = test('b--str1');
    var b2 = test('b--str2')
    console.log(await b1);
    console.log(await b2);
    console.timeEnd('b')
}
b();

输出结果:

a--str1
b--str1
b--str2
b: 1004.19384765625ms
a--str2
a: 2004.85498046875ms
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风舞红枫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值