what is promises in javascript 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: 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 3: promises in javascript

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

Example 4: promise js

A promise is an object that may produce a single value some time in the future: 
either a resolved value, or a reason that it’s not resolved

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: promise javascript

/*
Promise is a constructor function, so you need to use the new keyword to 
create one. It takes a function, as its argument, with two parameters - 
resolve and reject. These are methods used to determine the outcome of the
promise. 
The syntax looks like this:
*/

const myPromise = new Promise((resolve, reject) => {

});