Synchrony and Asynchrony in Javascript, Promises and Callback


Published on 30 April 2022


Synchrony and Asynchrony in Javascript, Promises and Callback

Explanation of what is synchrony and asynchrony in Javascript, Promises and Callback

Javascript is a single-threaded programming language that is executed sequence after sequence through a stack of calls made by any user. We can understand this usual concept used in javascript as a synchronous task.

An asynchronous task is that background task that is performed when a certain event occurs, that is, when a user executes a series of tasks, there will be some that are executed and others that are pending for some other task to happen. These background tasks will act asynchronously, without blocking the system, waiting for an event that can execute them. 
An example of an asynchronous task can be one that is waiting to be executed after a certain amount of time.

Javascript handles asyncs in several ways:

  • Callback. It is a function that controls the execution of functions just when the execution of another related task finishes. They can be synchronous or asynchronous. 
    Example: 
    We want through the "setTimeout" function to execute a message function after 2 seconds. This message function will be the "callback" function:

const message = function() {   
     console.log("This message after 2 seconds"); 
 } 
setTimeout(message, 2000);

The "callback" functions also happen with the execution of events, that is, when we press a button a function is executed that creates a new task:

<button id="call-btn">Click Here</button> 
   document.querySelector("#call-btn").addEventListener("click", function() {     
        console.log("Example callback event."); 
 });

  • Promises. It is a javascript object that has the function of performing a task in the future when it is required through a callback function. 
    Promises thus define their name since they have the objective of working in the same way as it does in reality, that is, as people we always promise actions to be carried out in the future with different people. 
    Example: I promise you that tomorrow I will go to play to basketball at 11 in the morning. 
    Therefore, the promises will have 3 states:
    • Slope
    • Solved
    • Refused

In the following image we can see how a promise works: 
Promises in Javascript lookkle.com

Example:

We create a promise object inside a function to check a name in which two values are taken to resolve or reject, if the condition is met or not it will give us an answer. The function will check itself afterwards and return the result with "then" in case of a successful response, and "catch" in case of an error.

<script type="text/javascript">
  function checkName(name){
   return new Promise((resolve,reject) => {
    if(name === 'lookkle') {    
     resolve('Promise is resolved');  
    } else {    
     reject('Promise is rejected');  
    }
   });
  }
  checkName('lookkle')
  .then(response => console.log(response))
  .catch(error => console.log(error));
</script>

With the promise object we can use the following functions:

  • Promise.all(iterable) → Receives an iterable of promises and returns one promise whose value is an array of values on success or the first failure reason if any fail
  • Promise.race(iterable) → Receive an iterable of promises and return a promise whose value is that of the first resolved if successful or the first failure reason if any fail
  • Promise.reject(reason) → Returns a rejected promise with the reason we specify
  • Promise.resolve(value) → Returns a resolved promise with the value that we specify

Promises with callback functions

Example of using promises with callback functions:

<script type="text/javascript">
const myVarFunction = (value) => {
 return new Promise((resolve, reject) => {
  if(value){
   resolve('Value is true');
  }else{
   reject('Value is false');
  }
 });
}

const functWin = (resul)=> {console.log(resul);}
const functError = (resul)=> {console.error(resul);}

myVarFunction(true).then(functWin).catch(functError);//Value is true
myVarFunction(true).then(functWin,functError);//Value is true
myVarFunction(false).then(functWin,functError);//Value is false
myVarFunction(false).then(functWin).catch(functError);//Value is false
</script> 

Promise Chaining

When we create a promise, it can return a successful result, which will be returned by "then", and that can be chained again with another "then" by the result given by the callback executed in the previous action, and so on.

Example:

<script type="text/javascript">
     new Promise((resolve, reject) => {
       setTimeout(() => {resolve(1)}, 1500);
     }).then((result) => {
         console.log(result);
         return result*2;
     }).then((result) => {
         console.log(result);
         return result*2;
     }).then((result) => {
         console.log(result);
         return result*2;
     }).then((result) => {
         console.log(result);
         return result*2;
     });
</script> 

It is also allowed to chain promises within promises:

<script type="text/javascript">
     new Promise((resolve, reject) => {
       setTimeout(() => {resolve(2)}, 1500);
     }).then((result) => {
         console.log('New promise declared');
         return new Promise((resolve, reject) => {
          setTimeout(() => {
             resolve(result*1);
             console.log(result);
           }, 500);
         });
     }).then((result) => {
         console.log(result);
         return result*2;
     }).then((result) => {
         console.log(result);
         return result*2;
     }).then((result) => {
         console.log(result);
         return result*2;
     });
</script>


Previous Chapter - Next Chapter



Tips on SEO and Online Business

Next Articles

Previous Articles