I've written a small program that compares the fulfillment of promises between the .then() approach and the async/await approach. The code runs correctly, however, the output was received in an unexpected order. Can someone please explain why the output is in its current order?
const backend = (num) => {
const someVar = new Promise((resolve, reject) => {
if (num % 2 === 0) {
resolve(`The number, ${num}, is even.`);
} else {
reject(`The number, ${num}, is odd.`);
}
})
return someVar;
}
const builtInFuncs = (num) => {
backend(num)
.then(message => console.log(message))
.catch(message => console.log(message));
}
const asyncAwait = async(num) => {
try {
const response = await backend(num);
console.log(response);
} catch (error) {
console.log(error);
}
}
builtInFuncs(2);
builtInFuncs(3);
asyncAwait(4);
asyncAwait(5);
The output I expected is:
The number, 2, is even.
The number, 3, is odd.
The number, 4, is even.
The number, 5, is odd.
The output I receive is:
The number, 2, is even.
The number, 4, is even.
The number, 5, is odd.
The number, 3, is odd.