Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between Callback function and Promise and Async awit

I Understand Callback Function but I cant understand promise method and async and await.why to use this three function in node js.can give explain for example code.

like image 422
smith hari Avatar asked Oct 18 '25 12:10

smith hari


1 Answers

Callback

Callback is a function that is passed as an argument to another function, and it is executed at the end. Like this:

function(callback){

   //you do some tasks here that takes time

   callback();
}

The callback is a method to deal with asynchronous code. For example, You may need to read a data form a file in your node app, and this process takes time. So, instead of blocking your code while reading, nodejs execute other tasks and then return back after the callback is executed.

Promise

The promise is also to deal with asynchronous code like callback method does but with more readable way. For example, instead of this:

example(function(){
    return example1(function(){
        return example2(function(){
            return example3(function(){
                done()
            })
        })
    })
})

It makes it more readable like this:

example()
    .then(example1)
    .then(example2)
    .then(example3)
    .then(done)

Async function / Await

The async function is used to write asynchronous code, specifically promises. inside of this function the keyword await is used to pause the execution of a promise until it is resolved. In other words, it waits for the promise to resolve and then resume the async function. For example:

async function example(){
    var data = await getData() // it waits until the promise is resolved
    return data;
}
like image 82
majid jiji Avatar answered Oct 21 '25 01:10

majid jiji