Async First?
Apart from learning async/await in C#, Node was the first JavaScript Async first framework that I encountered. If Node did it, then shouldn't we?
Converting to Async
Once we decide to convert our traditional Synchronous Components into Asynchronous components, we start to notice a few odd things. One of them is that single stepping to a line of code with an "await" will surprise us.
Anytime an "await" is seen it "yields" control to the async engine to do its thing. It most likely will not hit the next statement right away. Solution: Put in more breakpoints, just before and after "await" statements.
Pervasive throughout the Code Stack
Making our Functions Async tends to have a ripple effect upwards in the stack. Any async function requires the caller to "await" return, this means the caller must be asynchronous too. This often ripples up until perhaps maybe the entire stack becomes async.
Mixing Synchronous and Asynchronous
Yes it can be done but the recommendation is just be careful. For example, even event handlers themselves should become async.
// Before
onButtonClicked(event){
//do some synchronous work here
}
// After, browser gets control back immediately
async onButtonClicked(event){
await doSomeWork();
}
Lambda Conversion
// before
collection.map(item=>{ //do work here});
// after
collection.map(async(item)=>{
await workWithItem(item);
})
// using Promise resolve
collection.map(async(item)=>{
let newData = workWithItem(item)
await Promise.resolve(newData);
}
Closures
But just firing off Async requests may lead us to dependency trouble. If we encounter any dependencies along the way, we need to implement an Asynchronous closure.
// this is a closure on result.
let result = await getSomething(1);
// result must be complete before this statement
let result2 = await getSomething(2);
Integrate with Promises
async function getPromise(){
return await getSomethingThatReturnsOnlyPromises();
}
Awareness of the Team
When a team first looks at Async first they will be confused. It's not the same as Synchronous style programming. Be prepared to answer a few questions and to even roll back changes if the team leader doesn't go for it. They may not know it now but getting to all Async is a good design.
JWP2020 Async First
Top comments (1)
If you only have one
await
, and don't do anything after thatawait
, you can just omitasync
/await
inside the method.then it would look like this: