I was asked the following question in a JavaScript interview. I was unable to answer it. Please help!
const printString = (string, callback) => {
setTimeout(() => {
console.log(string);
callback();
}, Math.random() * 1000);
};
Call function printString three times with characters ‘a’, ‘b’ and ‘c’ and write a callback function such that a, b and c are printed in sequential order. Use the callback function however you want.
Any assistance is appreciated 🙂
4
Answers
To print the characters ‘a’, ‘b’, and ‘c’ in sequential order, you can use the callback function to chain the calls to
printString
. Here’s an example implementation:In this implementation, we define a new function
printInOrder
that takes an array of strings and an index as input. The index is used to keep track of which string to print next. If the index is equal to the length of the array, we stop the recursion.Inside the
printInOrder
function, we callprintString
with the current string and a callback function that callsprintInOrder
with the next index. This way, we chain the calls toprintString
and ensure that the strings are printed in sequential order.Finally, we call
printInOrder
with the array of strings and an initial index of 0 to start the recursion.You could wrap the call to
printString
in a promise and passres
as a callback. Whencallback
is executed inside thesetTimeout
, the promise gets resolved and it will move to the next item in the loop.The question is not completely clear to me since nothing is mentioned if we can use promise. I presume we can use it , so my solution will be to create a promise and then in the resolve we can call the callback
There is no need to use Promises, the simplest answer is to chain the
printString
method itself as a callback.Since its an interview question, the
Math.random()
is probably to deflect your mind into thinking that they will be called out of order, but they will be not.