All about Promise

Promise

  • Object that keeps track whether a certain event has happened already or not
  • Determines what happens after the event has stopped
  • Implements the concept of a future value that we’re expecting

States

Pending -> Event happens -> Settled/Resolved -> Fulfilled/Rejected

Example:


const getIDs = new Promise((resolve,reject) => {
  setTimeout(() => {
    resolve([23,43,87,12,46])
  }, 1500);
});
const getRecipe = recID => {
  return new Promise((resolve, reject) => {
    setTimeout(ID => {
      const recipe = {
        title: 'Fresh Apple',
        author: 'Abc'
      };
      resolve(`${ID}: ${recipe.title}`);
      }, 1500, recID);
    }
  );
};
getIDs
.then(IDs => {
  
  console.log(IDs);
  
  return getRecipe(IDs[2]);
})
.then(recipe => {
  console.log(recipe);
})
.catch(err => {
  console.log(err);
})

[Collected]

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s