Hello Im jofu and I’m struggling to manage asynchronous functions in JavaScript, especially with nested callbacks. I’ve heard about promises and async/await, but I’m not sure which is better for my case. Can someone explain the differences and help me decide when to use each?
There’s… no difference in the things you have mentioned. They are all parts of the operation.
A Promise is a reference holder for an asynchronous operation. It’s the thing you can check on to say “Are you done yet?” (Though you rarely if ever will.) without interrupting the main flow of the code. It’s the actual asynchronous operation from the outside perspective.
“async” is, i assume from context, a keyword in your function declaration that tells the compiler “I’m going to be doing some asynchronous stuff in this function”. Declaring a function async
is required to use the await
command within a function (otherwise you’re limited to using it at the global scope).
“await” is the command word to tell Javascript to… await. (Yeah, fancy naming and all, right?) await
means “The thing i’m about to tell you is an asynchronous operation. Wait until it’s done, then tell me the result”.
The contrast that you may have seen in your explorations is the difference between await
and then
. Which are two different ways of handling the same thing; waiting for a promise to get done, and then handling the result.
then
operates as a callback style. DoAThing().then((result) => { useTheResult; })
await
operates as an inline backfeed. result = await DoAThing()
Personally, I don’t use Promise as it confuses me if I have a lot of things going on. I just use await
-
Example of some code of a game I wrote →
const fetchNextId = async (currentId) => {
try {
// fetch the data from the server
const response = await fetch('get-next-id.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
current_id: currentId
})
});
// parse the response as JSON
const data = await response.json();
if (!data.end_of_table) {
id = data.next_id;
//console.log(id);
await changeImageSource(data.image);
await fetchWord();
await fetchQuestion();
} else {
// End of Game
let element = document.querySelector('.hangman');
while (element.firstChild) {
element.removeChild(element.firstChild);
}
console.log('End of Game');
await changeImage("/assets/canvas_images/img-game-over.jpg");
}
} catch (error) {
console.error(error);
}
};
I… but… you…do.
await
awaits the result of… a Promise.
fetch
returns a Promise.
So yes, you use Promise. You just arent overtly declaring one of your own.