Async-await feedback

hello -

i am trying to improve on an earlier post with an async/await example primarily to educate myself:

here is my example of async/await with chaining and error catching:

 async function asyncCounterFunction(counter) {
      try {
        return  ++counter;
      } catch(e) { console.error(e)
      }
  }
 
  async function testFunction(initialData) {
    const firstTime        = await asyncCounterFunction(initialData);      
    const secondTime       = await asyncCounterFunction(firstTime);
    const thirdTime        = await asyncCounterFunction(secondTime)
    console.info(await asyncCounterFunction(thirdTime))
    console.log('Completion!');
  }

testFunction(1);

this example was pieced together from many different sources.
does anybody have any suggested improvements? i am considering improving the example using setTimeout().

The main problem is, that there is absolutely no need for an async or await in the whole code.

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)

function writeHelloAfter1s(finishCallback)
{
    setTimeout(() =>
    {
        console.log("Hello");
        finishCallback();
    }, 1000);
}

function writeWorldAfter2s(finishCallback)
{
    setTimeout(() =>
    {
        console.log("World");
        finishCallback();
    }, 2000)
}

function main()
{
    console.log("Program started");
    writeHelloAfter1s(() =>
    {
        writeWorldAfter2s(() =>
        {
            console.log("Program finished");
        });
    });
}

main();

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();
3 Likes

thank you Thallius. i took your excellent example and changed it up a bit to illustrate some very simple parameter passing:

function asyncFunction(timeIn) {
   return new Promise( (resolve, reject) =>    {
        setTimeout(() => {
            resolve(++timeIn);   // resolve does the incrementing!
        }, timeIn * 1000);
   });
}

(async (value) => {  
          console.log('starting with: ', value);
          const firstResult  = await asyncFunction(value);
          const secondResult = await asyncFunction(firstResult);
          console.log('ending with:', secondResult);
})(1);

please let me know what you think.

1 Like

Looks like you got it. For me that’s fine.

I am a little bit old school :slight_smile: , that’s why I don’t like this notation

(async (value) => {
console.log('starting with: ', value);
const firstResult = await asyncFunction(value);
const secondResult = await asyncFunction(firstResult);
console.log(‘ending with:’, secondResult);
})(1)

Because the (1) can be overseen so easily and so you don’t see that the function is not only define but also called.
That’s why I would write

async main(value) => {
console.log('starting with: ', value);
const firstResult = await asyncFunction(value);
const secondResult = await asyncFunction(firstResult);
console.log(‘ending with:’, secondResult);
}
main(1);

But that is only personal taste

for anything written permanently, i wholeheartedly agree. but just for learning or illustration:

( (val) => { console.info('Thank you Thallius! ', val) })('passed')

there is something just so incredibly sexy about an anonymous function.:star_struck:

1 Like