this example was pieced together from many different sources.
does anybody have any suggested improvements? i am considering improving the example using setTimeout().
Yes I completely agree with you. Unfortunately, i am having a difficult time learning async/await because i am not very good with javascript. So i have to use a very simple example that is probably silly for the more technically gifted and advanced people.
This is really just an educational starting point. Once I have a good example to follow, the statements will be replaced with promises.
At the end async/await has made asynchronous code much easier.
Lets do an example code without async/await that prints āHelloā after 1s and āWorldā 2s after the āHelloā
(Yes you can do this much smarter but itās just an example)
You can imagine how complicated it will be when you have more nested command depending on the result of the command before.
With async/await and Promises this looks so much smarter:
function writeHelloAfter1s()
{
return new Promise(resolve =>
{
setTimeout(() =>
{
console.log("Hello");
resolve();
}, 1000);
});
}
function writeWorldAfter2s()
{
return new Promise(resolve =>
{
setTimeout(() =>
{
console.log("World");
resolve();
}, 2000);
});
}
async function main()
{
console.log("Programm started");
await writeHelloAfter1s();
await writeWorldAfter2s();
console.log("Program finished");
}
main();