async和await的使用示例

175 阅读1分钟

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

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()

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

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

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

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