Skip to content

Instantly share code, notes, and snippets.

@aungthuoo
Last active May 19, 2024 16:04
Show Gist options
  • Save aungthuoo/93eccf3ab51cd6347e7a7aa7a3b10356 to your computer and use it in GitHub Desktop.
Save aungthuoo/93eccf3ab51cd6347e7a7aa7a3b10356 to your computer and use it in GitHub Desktop.

JavaScript Promise

A promise is an object that will produce a single value sometime in the future. If the promise is successful, it will produce a resolved value, but if something goes wrong then it will produce a reason why the promise failed.

Simply said:- It behaves very much similar to real life promises.

// promises
let fruits = ["apple", "banana", "orange"];

const animateOne = (fruit, animate) => {
  return new Promise((res, rej) => {
    setTimeout(() => {
      animate(fruit);
      res(true);
    }, 1000);
  });
};

const animateAll = (animate) => {
  animateOne(fruits[0], animate)
    .then(() => animateOne(fruits[1], animate))
    .then(() => animateOne(fruits[2], animate))
    .catch((err) => console.log("some error occured", err));
};

const animate = (fruit) => {
  console.log("calling", fruit);
};

animateAll(animate); 

Output:

calling apple
calling banana
calling orange
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment