create a promise javascript 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: promise catch

//create a Promise
var p1 = new Promise(function(resolve, reject) {
  resolve("Success");
});

//Execute the body of the promise which call resolve
//So it execute then, inside then there's a throw
//that get capture by catch
p1.then(function(value) {
  console.log(value); // "Success!"
  throw "oh, no!";
}).catch(function(e) {
  console.log(e); // "oh, no!"
});

Example 4: 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 5: promises in javascript

myPromise.then(
  function(value) { /* code if successful */ },
  function(error) { /* code if some error */ }
);

Example 6: making promises in js

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