Promise任务队列,async/await

**1.实现原理**

如果 then 返回promise 时,后面的then 就是对返回的 promise 的处理

下面使用 map 构建的队列,有以下几点需要说明
1.then 内部返回的 promise 更改外部的 promise 变量

2.为了让任务继承,执行完任务需要将 promise 状态修改为 fulfilled

function queue(nums) {
  let promise = Promise.resolve();
  nums.map(n => {
    promise = promise.then(v => {
      return new Promise(resolve => {
        console.log(n);
        resolve();
      });
    });
  });
}

queue([1, 2, 3, 4, 5]);

下面再来通过 reduce 来实现队列

function queue(nums) {
  return nums.reduce((promise, n) => {
    return promise.then(() => {
      return new Promise(resolve => {
        console.log(n);
        resolve();
      });
    });
  }, Promise.resolve());
}

queue([1, 2, 3, 4, 5]);

async/await

使用 async/await 是promise 的语法糖,可以让编写 promise 更清晰易懂,也是推荐编写promise 的方式。

async/await 本质还是promise,只是更简洁的语法糖书写

async/await 使用更清晰的promise来替换 promise.then/catch 的方式

 async function hd(){
      return "houdunren.com";
  }
  console.log(hd());//promise
  hd().then(value => {
  console.log(value);//hourunren
});

如果有多个await 需要排队执行完成,我们可以很方便的处理多个异步队列

async function hd(message) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(message);
    }, 2000);
  });
}
async function run() {
  let h1 = await hd("后盾人");
  console.log(h1);
  let h2 = await hd("houdunren.com");
  console.log(h2);
}
run();

await
使用 await 关键词后会等待promise 完

1. await 后面一般是promise,如果不是直接返回

2. await 必须放在 async 定义的函数中使用
3. await 用于替代 then 使编码更优雅

async function hd() {
  const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("houdunren.com");
    }, 2000);
  });
  let result = await promise;
  console.log(result);
}
hd()

一般await后面是外部其它的promise对象

async function hd() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve("fulfilled");
    }, 2000);
  });
}
async function run() {
  let value = await hd();
  console.log("houdunren.com");
  console.log(value);
}
run();

下面是使用async 设置定时器,并间隔时间来输出内容

async function sleep(ms = 2000) {
  return new Promise(resolve => {
    setTimeout(resolve, ms);
  });
}
async function run() {
  for (const value of ["后盾人", "向军"]) {
    await sleep();
    console.log(value);
  }
}
run();

类中使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值