简体   繁体   中英

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

I am very new to asynchronous JavaScript. I am trying to add a new member to a zoo and then display the updated list of zoo animals in the following code. the new animal is being admitted successfully but the method to display updated list of zoo animals is not working. Can anyone plz point out what is going on here?

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

resolve and reject in the Promise constructor are functions. With async/await syntax, you call resolve with the value to return to the function that is await-ing or call reject with an object to throw.

Your code is in charge of determining when an error has occurred to decide whether to call resolve or 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM