Javascript: Promise, Await/Async and Closure

 

So been seeing these two pops up in the Javascript world, and finally gave it time to study what they are.

Closure , basically a term in Javascript where a value in a function is retained.

This is when you pass a value to a function and the function itself is returned. The value that you pass to the main function gets stored inside the sub-function.

And when its finally time to call the returned (function), every variables stored is kept. See the link below for more information, and skip to 10:00 to actually see whats happening.

Promise a new concept, and only available from EcmaScript 2015 or ES6. It is an object that receives a function with 2 parameters, a resolve and  reject function parameters. Then use the “.then(function(return_from_resove){})” when the promise call the “resolve(pass))” inside it, the “then” will be triggered according to what was called. It is like a true or false ,and to promise to return true or to return false. You use “catch(function(){})” chaining when “reject()” is invoke. Here is a quick snippet of the promise:

let promise = new Promise(function(resolve,reject){
       if(true) resolve("anything");
       else if(false) reject("anything");
}).then(function(from_resolve_value{
   // Do anything here
}).catch(function(from_reject_value)){
    // Do anything here
})

Below are excellent video explaining how it works.

Await/Async is a ECMASCRIPT 2017 (ES8) feature that would let you set a function to be asynchronous.

You need to set your function with async and can only use await inside this type of function example below:

async my_function(){
     var result = await getting_json();
     // Im dont waiting let see the result
     console.log ("Im done");
}
my_function(); // Asynchronous function
console.log("Im not waiting for my_function to finish"); // This will trigger straight away 

// You can also return promise in a async function
func_promise(){
    var prom = new Promise((resolve,reject) => resolve() // or call reject if error);
    return prom;
}
func_promise().then(alert("Success") ).catch(alert("Failed!"));

// You dont need to use promise with async/await they are both asynchronous

A good article about async/await:

https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9

[Update: May/2018 – NodeJS  version 8] Supports ASYNC/AWAIT function.

Leave a Reply

Your email address will not be published. Required fields are marked *