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.
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.
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)
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With