I am doing some exercises on async/await
and I am completely blank on this one:
The
opA
function must be called before opB
, and opB
must be called beforeopC
. Call functions such a way thatC
thenB
thenA
is printed out.
const print = (err, contents) => {
if (err) console.error(err)
else console.log(contents )
}
const opA = (cb) => {
setTimeout(() => {
cb(null, 'A')
}, 500)
}
const opB = (cb) => {
setTimeout(() => {
cb(null, 'B')
}, 250)
}
const opC = (cb) => {
setTimeout(() => {
cb(null, 'C')
}, 125)
}
My guess is there is a typo in the question, so I should just have the functions print out A B C
and not C B A
?
My attempt is this:
(async function () {
await print(opA());
await print(opB());
await print(opC());
}());
but I get
cb(null, 'C')
^
TypeError: cb is not a function
Question
I have literally no idea how to solve this one, and don't understand the usage of the print
function.
Any help on how to get me going will be much appreciated =)
You said this is an async/await exercise but the code you show is the complete antithesis of async/await - it uses the callback paradigm.
To make your code print C B A
you would need to pass callbacks to the opX
functions in such an order to make them print their results:
const print = (err, contents) => {
if (err) console.error(err)
else console.log(contents )
}
const opA = (cb) => {
setTimeout(() => {
cb(null, 'A')
}, 500)
}
const opB = (cb) => {
setTimeout(() => {
cb(null, 'B')
}, 250)
}
const opC = (cb) => {
setTimeout(() => {
cb(null, 'C')
}, 125)
}
opA(print);
opB(print);
opC(print);