I just started using async/await and is confused on how it interacts with callback. For example,
fooMethod(function() {
return Promise.resolve("foo");
});
vs
fooMethod(async function() { //add async keyword
return "foo";
});
Must fooMethod be written in a specific way so that it can handle an async
function as callback?
if fooMethod
is a public library, how do I know that it is safe to add async
keyword to the function?
FOLLOW UP
Express router,
app.get('/foo', function (req, res) {
return res.send("foo");
});
app.get('/foo', async function (req, res) {
return res.send("foo");
});
both of these function works, is it safe to use though?
Asynchronous callbacks are functions passed to another function that starts executing code in the background. Typically, when the code in the background finishes, the async callback function is called as a way of notifying and passing on data to the callback function that the background task is finished.
A callback is just a function that's passed into another function, with the expectation that the callback will be called at the appropriate time. As we just saw, callbacks used to be the main way asynchronous functions were implemented in JavaScript.
Using callbacks, we can begin to separate – with a callback, we can load the data and, when the asynchronous operation is done, run the callback function. It does keep them nicely separated and it does pass the data into the callback as a parameter.
Async/Await is used to work with promises in asynchronous functions. It is basically syntactic sugar for promises. It is just a wrapper to restyle code and make promises easier to read and use. It makes asynchronous code look more like synchronous/procedural code, which is easier to understand.
Your two callbacks are equivalent. An async function
is just syntactic sugar for a regular function
that returns a Promise
. This means that you can call an async function
like a regular function. Here’s a demo:
const foo = async function (arg) {
return arg * 2
}
const bar = function (arg) {
return Promise.resolve().then(() => {
return arg * 2
})
}
const fooReturn = foo(2)
const barReturn = bar(2)
console.log('foo(2) =>', fooReturn.toString())
console.log('bar(2) =>', barReturn.toString())
fooReturn.then(fooResult => console.log('await foo(2) =>', fooResult))
barReturn.then(barResult => console.log('await bar(2) =>', barResult))
However, if the code that takes the callback wants to get a response, you won’t be able to use an async function unless the code is specially designed to check the return value of the callback function and await
it if it’s a Promise
.
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