Created
August 8, 2024 06:23
-
-
Save OlivierJM/f858f8037f03be558e00b6b9c4b22481 to your computer and use it in GitHub Desktop.
Show how to use promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fetchData = () => { | |
return new Promise((resolve, reject) => { | |
// Here we are simulating an action that would likely take time, basically it doesn't run immediately | |
// it could be something like long calculations, fetching data from a server, writing data to a file, etc ... | |
setTimeout(() => { | |
const success = true; // this is just to simulate a successful action | |
if (success) { | |
// if we succeed then we mark as resolved | |
resolve('Data fetched successfully!'); | |
} else { | |
// else we reject because the promise wasn't fullfilled | |
reject('Failed to fetch data.'); | |
} | |
}, 2000); | |
}); | |
}; | |
// Then yiu use the fetchData this way | |
fetchData() | |
.then((message) => { | |
console.log(message); // Data fetched successfully! | |
}) | |
.catch((error) => { | |
console.error(error); // Failed to fetch data. | |
}).finally(() => { | |
// this will run regardless of the outcome of the promise, consider it like deadline yafika whether you did what was agreed or not here it doesn't matter, it finished | |
}); | |
// You could also do it this way. this is equivalent to the above code | |
async function someFetch() { // Note the async keyword used here | |
try { | |
const result = await fetchData(); // also note the await keyword used here | |
// result here will contain the resolved response from the promise | |
console.log(result); // Data fetched successfully! | |
} catch (error) { // Failed to fetch data. | |
// error will contain the rejected response from the promise | |
} finally { | |
// this will run regardless of the outcome of the promise | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment