This has to be the biggest problem I face when using JS.
It’s not like VB, VBScript, BAT, BAS, C# or other serial, linear programming languages.
It drives me crazy.
I’m still of the opinion that all code should still be sequential by default, and if you want a function to be async, then you should just tell that specific call to be async, rather than the other way around. An opt in, rather than “you’re already in and tough luck”.
To make like easier (and I’ve stolen this code to post here, as it makes life easier and so I can find it again later) here is some code of a working practical example.
Serial or Chaining Flow
If you want to execute different promise methods sequential i.e. execute one by one, it is easy using Async/Await and the code looks like synchronous.
async function SerialFlow(){ let result1 = await doJob(1,1); let result2 = await doJob(2,2); let result3 = await doJob(3,3); let finalResult = result1+result2+result3; console.log(finalResult); return finalResult; } SerialFlow(); |
In above method first 1 is executed and wait for one sec then 2 is started wait for 2 seconds after that 3 started to execute. 1,2,3 are executed sequentially, hence the total time is 6 seconds.
Console Output:
Start: 1 End: 1 Start: 2 End: 2 Start: 3 End: 3 6 |
Just about every other example online gives non-practical examples and use promises, observables, awaits, asyncs, call-back hell, jargon that mostly doesn’t make sense. I hope this very simple example will help you.
Here is my very crude example of partially working code, of which you can see there are things going on.
async function getpostcoderegion(state)
}
return 1;
// RUN THE MAGIC FROM THIS FUNCTION.
Leave a Reply