Often you find yourself using async code and handling delayed response in JavaScript
There are two well known approaches that are often used
* Callbacks. This is the conventional way, and is frankly annoying. I won't say much more about these.
* Promises. Of course they are all the rage right now. They are lovely. doSomething().then(doAnother()) etc. The only issue is that when processing promise code you have to deal with creating and returns functions and callback-like syntax still, and soon code starts to look busy again
So, if you are in NodeJS, you have a few options to use async..await pattern. Here I use the asycnawait library. Other options are co, async etc.
The idea is quite simple. You write a function inside async(). Within the function, write code as if it's synchronous, and use await() to resolve promises.
Example
let yourFunction = function() {
var result = await(functionThatReturnsPromise());
return result; // when called with async() this will return a promise automatically
}
// get async'able function using 'async'
var finalResult = async(yourFunction);
// now call it
finalResult.then(...).catch(...)
That's it! The code is much simpler with some automatic promise'ing going on for you.
code().then(relax)
Note: if you are in client side code, you can use (with IE being the exception) aysnc await already. See the MDN article on async for ref
References:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
* https://github.com/yortus/asyncawait
There are two well known approaches that are often used
* Callbacks. This is the conventional way, and is frankly annoying. I won't say much more about these.
* Promises. Of course they are all the rage right now. They are lovely. doSomething().then(doAnother()) etc. The only issue is that when processing promise code you have to deal with creating and returns functions and callback-like syntax still, and soon code starts to look busy again
So, if you are in NodeJS, you have a few options to use async..await pattern. Here I use the asycnawait library. Other options are co, async etc.
The idea is quite simple. You write a function inside async(). Within the function, write code as if it's synchronous, and use await() to resolve promises.
Example
let yourFunction = function() {
var result = await(functionThatReturnsPromise());
return result; // when called with async() this will return a promise automatically
}
// get async'able function using 'async'
var finalResult = async(yourFunction);
// now call it
finalResult.then(...).catch(...)
That's it! The code is much simpler with some automatic promise'ing going on for you.
code().then(relax)
Note: if you are in client side code, you can use (with IE being the exception) aysnc await already. See the MDN article on async for ref
References:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
* https://github.com/yortus/asyncawait
Comments
Post a Comment