簡體   English   中英

這個異步等待代碼(javascript)有什么問題?

[英]What is wrong with this async-await code (javascript)?

我對異步 JavaScript 很陌生。 我正在嘗試向動物園添加新成員,然后在以下代碼中顯示更新后的動物園動物列表。 新動物被成功錄取,但顯示動物園動物更新列表的方法不起作用。 誰能指出這里發生了什么?

let zoo = [
  { animal: "elephant", age: 15 },
  { animal: "rhino", age: 10 },
  { animal: "tiger", age: 6 },
];

const admit = (animal) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      zoo.push(animal);
      resolve: console.log(
        `new ${animal.animal} added. now ${zoo.length} animals.`
      );
      //reject: console.log("something went wrong");
    }, 2000);
  });
};

const displayZoo = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve: console.table(zoo);
      reject: console.log("something went wrong while displaying animals");
    }, 3000);
  });
};

const doSomething = async () => {
  try {
    let admission = await admit({ animal: "lion", age: 13 });
    await displayZoo();

    console.log("everything went fine");
  } catch (err) {
    console.log(err);
  }
};

doSomething();

Promise構造函數中的resolvereject是函數。 使用 async/await 語法,您可以使用值調用resolve以返回到正在等待的 function 或使用 object 調用reject以拋出。

您的代碼負責確定何時發生錯誤以決定是調用resolve還是reject

let zoo = [
  { animal: "elephant", age: 15 },
  { animal: "rhino", age: 10 },
  { animal: "tiger", age: 6 },
];

const admit = (animal) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      zoo.push(animal);
      resolve(`new ${animal.animal} added. now ${zoo.length} animals.`);
      // `await admit()` will return this string ^
    }, 2000);
  });
};

const displayZoo = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (Math.random() > 0.5) { // To simulate some failure condition
          console.table(zoo);
          resolve();
          // `await displayZoo()` will return undefined (void function)
      } else {
          reject('There was an error');
          // `await displayZoo()` will throw this string ^
      }
    }, 3000);
  });
};

const doSomething = async () => {
  try {
    let admission = await admit({ animal: "lion", age: 13 });
    console.log(admission);
    await displayZoo();

    console.log("everything went fine");
  } catch (err) {
    console.log(err);
  }
};

doSomething();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM