new 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: 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 3: js return a promise

function myAsyncFunction(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.onload = () => resolve(xhr.responseText);
    xhr.onerror = () => reject(xhr.statusText);
    xhr.send();
  });
}

Example 4: .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"));
  }
});

Example 5: making promises in js

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