How to recognise when we need the use of await keyword

Hello, consider this code:
async function onSubmit() {
const url = "https://pokeapi.co/api/v2/ability/?limit=5&offset=5";
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Request unsuccessful, status code: ${response.status}`);
}
const result = await response.json();
console.log(result);
} catch (error) {
console.error(error);
}
}
async function onSubmit() {
const url = "https://pokeapi.co/api/v2/ability/?limit=5&offset=5";
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Request unsuccessful, status code: ${response.status}`);
}
const result = await response.json();
console.log(result);
} catch (error) {
console.error(error);
}
}
Notice I used await for fetch() and response.json(). I did use that because it's how it's written on MDN but beside that, when do we know something is asynchronous in nature?
4 Replies
13eck
13eck2mo ago
It’s very simple: any time a function returns a Promise it’s asynchronous. You either await it or chain .then() methods capped with a .catch() of course
Faker
FakerOP2mo ago
yup noted, thanks !
13eck
13eck2mo ago
Just check the docs for the API you’re using and you’ll know. For example, the fetch API: https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch#return_value
No description
Faker
FakerOP2mo ago
yep just did that

Did you find this page helpful?