javascript make promise code example

Example 1: js create a promise

/*
	A Promise is a proxy for a value not necessarily known when the promise is created. 
    It allows you to associate handlers with an asynchronous action's eventual success 
    value or failure reason.
*/            
let promise = new Promise((resolve , reject) => {
  fetch("https://myAPI")
    .then((res) => {
      // successfully got data
      resolve(res);
    })
    .catch((err) => {
      // an error occured
      reject(err);
    });          
});

Example 2: javascript promise

var promise = new Promise(function(resolve, reject) {
  // do some long running async thing…
  
  if (/* everything turned out fine */) {
    resolve("Stuff worked!");
  }
  else {
    reject(Error("It broke"));
  }
});

//usage
promise.then(
  function(result) { /* handle a successful result */ },
  function(error) { /* handle an error */ }
);

Example 3: javascript create promise

// base case
const promise = new Promise(executor);

// more complex example
const coinflip = (bet) => new Promise((resolve, reject) => {
  const hasWon = Math.random() > 0.5 ? true : false;
  if (hasWon) {
    setTimeout(() => {
      resolve(bet * 2);
    }, 2000);
  } else {
    reject(new Error("You lost...")); // same as -> throw new Error ("You lost ...");
  }
});

Example 4: making promises in js

getData()
    .then(data => console.log(data))
    .catch(error => console.log(error));

Example 5: what is promise in javascript

Promises make async javascript easier as they are easy to use and write than callbacks. Basically , promise is just an object , that gives us either success of async opertion or failue of async operations

Example 6: javascript promises

var posts = [
  {name:"Mark42",message:"Nice to meet you"},
  {name:"Veronica",message:"I'm everywhere"}
];

function Create_Post(){
  setTimeout(() => {
    posts.forEach((item) => {
      console.log(`${item.name} --- ${item.message}`);
    });
  },1000);
}

function New_Post(add_new_data){
  return new Promise((resolve, reject) => {
    setTimeout(() => {
     posts.push(add_new_data);
      var error = false;
      if(error){
        reject("Something wrong in </>, Try setting me TRUE and check in console");
      }
      else{
        resolve();
      }
    },2000);
  })
}

New_Post({name:"War Machine",message:"I'm here to protect"})
    .then(Create_Post)
    .catch(err => console.log(err));

Tags:

Misc Example