async和await的使用示例

一个关于猜大小的代码示例promise

function 猜大小(猜想) {
  return new Promise((resolve, reject) => {
    console.log('开始摇色子');
    setTimeout(() => {
      let n = parseInt(Math.random() * 10 + 1, 10);
      if (n > 5) {
        if (猜想 === "大") {
          resolve(n);
        } else {
          reject(n);
        }
      } else {
        if (猜想 === "小") {
          resolve(n);
        } else {
          reject(n);
        }
      }
    }, 3000);
  });
}

async function asyncCall() {
  try {
    let n = await 猜大小("大");
    console.log("我赢了" + n);
  } catch (error) {
    console.log("输光了" + error);
  }
}

asyncCall();
复制代码

固然以上的是每次执行的都是一次猜大小的结果,若是我须要的是屡次猜大小的结果呢?那么可使用 promise.all()bash

async function asyncCall() {
  try {
    let n = await Promise.all([猜大小("大"),猜大小("大")]);
    console.log("我赢了" + n);
  } catch (error) {
    console.log("输光了" + error);
  }
}
复制代码

上面的代码表示的就是等待屡次猜大小的执行结果,若是只是须要屡次猜大小中的一个结果就好?那么可使用Promise.race()dom

async function asyncCall() {
  try {
    let n = await Promise.race([猜大小("大"),猜大小("大")]);
    console.log("我赢了" + n);
  } catch (error) {
    console.log("输光了" + error);
  }
}
复制代码

async表示的是声明一个异步函数,await表示的是接受函数返回的隐式promise结果。 trycatch配合使用。异步

相关文章
相关标签/搜索