javascript promises explained code example

Example 1: 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 2: 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 3: js promise examples

//Promise to load a file...
//use with openFile(url, fCallback);
//fCallback(fileContents){ //do something with fileContents}
const loadFile = url => {
    return new Promise(function(resolve, reject) {
        //Open a new XHR
        var request = new XMLHttpRequest();
        request.open('GET', url);
        // When the request loads, check whether it was successful
        request.onload = function() {
            if (request.status === 200) {
                // If successful, resolve the promise
                resolve(request.response);
            } else {
                // Otherwise, reject the promise
                reject(Error('An error occurred while loading image. error code:' + request.statusText));
            }
        };
        request.send();
    });
};
const openFile = (url, processor) => {
    loadFile(url).then(function(result) {
            processor(result);
        },
        function(err) {
            console.log(err);
        });
};

Example 4: promises in javascript

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

Example 5: promise javascript

const promiseA = new Promise( (resolutionFunc,rejectionFunc) => {
    resolutionFunc(777);
});
// At this point, "promiseA" is already settled.
promiseA.then( (val) => console.log("asynchronous logging has val:",val) );
console.log("immediate logging");

// produces output in this order:
// immediate logging
// asynchronous logging has val: 777

Example 6: making promises in js

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

Tags:

Misc Example