Promises

Added in ES 2015.
A promise is an object that represents the eventual result of an asynchronous operation.


A promise can only have 2 outcomes - either success or fail
Promises allow us to string together multiple chained callbacks while making the code easier to read.



This resolves the fundamental problem that callbacks have.


A promise is an object that represents the eventual result of an asynchronous operation.


It has a state property
It has a result property.
It has a resolve method.
It has a reject method.
A promise can only suceed or fail once


Promise Object


let mypromise = new Promise(function(resolve, reject) { 
// do something
// if everything has worked
   if (true) {
      resolve(result);
   } else {
      reject(error);
   }
});


function getData(d){ 
   return new Promise(function(resolve, reject) {
      setTimeout(function(){ resolve(d); }, 1000);
   });
}

getData(50)
   .then(function(answer){
      console.log(answer);
});

With or without the Arrow Function

   return new Promise(function(resolve, reject) { 
or
   return new Promise( (resolve, reject) => {


Promises are similar to Event Listeners with a few important differences.
Lets you separate the parameters from the function code.


function myFunction() { 
   return new Promise(function(resolve, reject) {
      setTimeout( () => resolve("Return This String") , 1000);
   })
   .then(function() {
      console.log(theResult);
   });
}
myFunction();


Nested Callback Syntax

function asyncMethod(message) { 
  return new Promise( function (succeed, fail) {
    setTimeout( function() {
      console.log(message);
      succeed();
     }, 400)
  });
}

asyncMethod('Connect to Database').then( function() {
  asyncMethod('Verify User Details').then( function() {
    asyncMethod('Check Permissions').then( function() {
      asyncMethod('Update User').then( function() {} )
    })
  })
})


? Syntax

function fn_verifyUserDetails() { 
  asyncMethod('Verify User Details')
    .then( fn_checkPermissions )
}
function fn_checkPermissions() {
  asyncMethod('Check Permissions')
    .then( fn_updateUser )
}
function fn_updateUser() {
  asyncMethod('Update User')
    .then( function () {} )
}
asyncMethod('Connect to Database')
  .then( fn_verifyUserDetails )


Chaining Syntax (Reference)

function fn_verifyUserDetails() { 
  return asyncMethod('Verify User Details')
}
function fn_checkPermissions() {
  return asyncMethod('Check Permissions')
}
function fn_updateUser() {
  return asyncMethod('Update User')
}
asyncMethod('Connect to Database')
  .then( fn_verifyUserDetails )
  .then( fn_checkPermissons )
  .then( fn_updateUser )
  .then( function () {} )


© 2022 Better Solutions Limited. All Rights Reserved. © 2022 Better Solutions Limited TopPrevNext