JavaScript Promise

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        

View more : https://softwarezay.com/posts/javascript-promise@202405-19

要查看或添加评论,请登录

社区洞察

其他会员也浏览了