11

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?

asked Jul 18, 2017 at 19:44
9
  • There is no point of using async when you don't await Commented Jul 18, 2017 at 20:08
  • @RoyiNamir this is just a simple example, I was just confuse on the interaction with callback of a possibly public library Commented Jul 18, 2017 at 20:12
  • fooMethod must be written in a specific way, it must handle promise returning function. If it doesn't, none of your examples work, if it does then both examples work. Commented Jul 18, 2017 at 20:15
  • @TamasHegedus That’s incorrect — if the function doesn’t do anything with the return value, then it doesn’t need to handle returned Promises differently. Commented Jul 18, 2017 at 20:23
  • @JF you mean if the function just ends with cb() then we are safe to add async keyword but if the functtion ends with const result = cb() then it will not support async keyword unless it resolve the promise from the callback? Commented Jul 18, 2017 at 20:30

2 Answers 2

4

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.

answered Jul 18, 2017 at 20:02
Sign up to request clarification or add additional context in comments.

8 Comments

Hi, so when can I know I can't use async keyword in a callback?
@Zanko I’ve edited my answer; does the edit clarify that issue?
i have edited my answer, do you mind clarifying the follow up? Thank you so much!
Yep, that should be safe @Zanko. Express controllers like those are meant to be asynchronous.
Thanks, I posted a comment too : ) Hope you can verify that!
|
1

Your two functions are equivalent, but below demonstrates how using await in an async function delays the function execution by an extra tick each time:

function syncTest() {
 console.log('sync completed')
 return Promise.resolve('foo')
}
async function asyncTest() {
 console.log('async completed')
 return 'foo'
}
async function awaitTest() {
 console.log('await started')
 await void 0
 console.log('await awaited')
 await void 0
 console.log('await completed')
 return 'foo'
}
console.log('start')
syncTest().then(value => console.log(`sync resolved: ${value}`))
asyncTest().then(value => console.log(`async resolved: ${value}`))
awaitTest().then(value => console.log(`await resolved: ${value}`))
Promise.resolve()
 .then(() => console.log('tick 2 completed'))
 .then(() => console.log('tick 3 completed'))
 .then(() => console.log('tick 4 completed'))
console.log('tick 1 completed')

answered Jul 18, 2017 at 20:55

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.