DEV Community

Cover image for Modern JS Talk async function
Kenta Takeuchi
Kenta Takeuchi

Posted on • Originally published at bmf-tech.com

Modern JS Talk async function

This article was originally published on bmf-tech.com.

※This article is a reprint from the Innovator Japan Engineers’ Blog.

What is async function

An async function is a function that returns an Async Function object.

By using the keywords async and await, you can write asynchronous processing more concisely than with Promises.

The specification was defined in ES2017.

How to Use

It's easy to use.

Simply add the async keyword at the beginning of the function definition.

If you define it to return a value other than a Promise, a Promise resolved with that value will be returned.

async function asyncFunc() {
    return 'Amazing!';
}

asyncFunc().then((result) => {
    console.log(result);
});
Enter fullscreen mode Exit fullscreen mode
async function asyncFuncB(text) {
    return 'Amazing!' + text;
}

asyncFuncB('Indeed!').then((result) => {
    console.log(result);
});
Enter fullscreen mode Exit fullscreen mode

Of course, you can also return a Promise.

async function asyncFuncC() {
  return new Promise((resolve, reject) => {
    resolve('Wonderful!');
  });
}

asyncFuncC().then((result) => {
  console.log(result);
});
Enter fullscreen mode Exit fullscreen mode

Incidentally, the above can be rewritten as follows.

async function asyncFuncC() {
    return Promise.resolve('Wonderful!')
}

asyncFuncC().then((result) => {
    console.log(result);
});
Enter fullscreen mode Exit fullscreen mode

Also, within an async function, you can use the await keyword.

The await keyword is an operator that can pause the execution until the Promise's result is returned.

By using the await keyword, you can omit the Promise.then()~ part.

 

async function awaitFunc() {
    return 'Wonderful!';
}

async function asyncFuncD() {
    let result = await awaitFunc();
  console.log(result);
}

asyncFuncD();
Enter fullscreen mode Exit fullscreen mode

Impressions

By using the async keyword, you can create functions that return Promises concisely without having to write Promises repeatedly, making asynchronous processing easier to implement.

References

Top comments (0)