Callbacks and Promises

 

 Callbacks

 

In JavaScript, functions are objects. We can pass object as parameter so we can also pass functions as parameters to other functions and call them inside the outer functions.

function hello() { 

    conole.log(“hello world”);

}

 

function print(callback) { 

         //other codes are running here

         //call hello function, the  all execution finished from this line

    callback();

}

 

Print(hello());

New learn: object can pass as a parameter to a function this mean at function declaration time object was inserted as parameter to function and it can be used inside the outer function. In this example “createPost” is a function that is takes “post” as object parameter then at the time of calling argument pass as object into function declaration and it is inserted to the post array by “push” methods

 Post one and post two only displayed in the browser post three is not there. In this example after complied the “getPost” function “createPost” function is called so “post three” inserted after display the function through “getPstot” that is the reason Post three is not display to the browser. Solution for this problem is needed to use callback methods to the function.





In java functions are object. This object passed to the parameter this will be called after complete the particular function which is priority for this function. In the example “createPost” have two parameter one is post other one is callback post taking post three data callback taking “getPost” function this function calling inside the outer function after give priority code is executed. In this example callback called after push the data into array. Right after push function callback will be execute it will not wait 2 second



Output for above function



Promises

In this example first, videoOne will record and second, videoTwo will record and third, videoThree will record. After compiled all function in the squire bracket then “then function” start to work. The promise will be return two values one is resolve and other one is reject. We can use this both value when we need at the situation. If we want to give a success full massage “resolve” key word will be used on other hand if we want a failure massage “reject” key word will be used.



 


 

 

Comments