Skip to content

Instantly share code, notes, and snippets.

@ponyjackal
Last active November 16, 2020 10:39
Show Gist options
  • Save ponyjackal/6e84795418770334af09752a56cea2cd to your computer and use it in GitHub Desktop.
Save ponyjackal/6e84795418770334af09752a56cea2cd to your computer and use it in GitHub Desktop.
Async/Await in Javascript
The keyword async was implemented in ES2017. It makes it possible to create naturally asynchronous functions using the following notation:
async function myAsyncFunction() {}
Something important and even more interesting about this implementation is that every async function returns a Promise, meaning that we can use all the interfaces we already know in the article about promises. Let's look at an example to better understand:
async function myAsyncFunction() {
return "Hello!";
}
myAsyncFunction().then(payload => {
console.log(payload); // Hello!
});
The async functions use the success values as the values that will be arranged within the.then pipeline in the promise that will be returned, in case you need to export an error, it is necessary to trigger an error within the scope of execution to be sent to the .catch pipeline, let's see an example:
async function myAsyncFunctionWithError() {
throw "something wrong happen";
}
myAsyncFunctionWithError().catch(error => {
console.log(error); // something wrong happen
});
Await
The use of await is restricted only within a function declared with the keyword async, basically what it does is wait for the Promise response value or convert the value into a resolved Promise.
async function myAsyncFunction() {
const payload = await { name: "felipe", age: 22 };
console.log(payload); // { name: 'felipe', age: 22 }
}
myAsyncFunction();
In cases where we are not returning any value from our function, the execution call remains as normal function calls without using .then.
Catching errors with try/catch
Await always expects the success value of the promise, so we have no way to capture the error directly, to do this we have to make use of the try/catch which receives the reject value if it happens, within the promises that are being executed inside the try block:
async function myAsyncErrorFunction() {
throw "ops, something wrong happen";
}
async function myAsyncFunction() {
try {
const response = await myAsyncErrorFunction();
} catch (error) {
console.log(error); // ops, something wrong happen
}
}
myAsyncFunction();
Executing this block, the error happens inside the promise myAsyncErrorFunction and is captured inside the try/catch catch block.
In summary, the joint use of the implementations makes our code extremely simple and readable, making handling asynchronous (or synchronous) data more directly and effectively.
I hope you enjoyed this series, see you later!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment