• Skip to primary navigation
  • Skip to main content
Sal Ferrarello
  • About Sal Ferrarello
  • Speaking
  • Connect
    Mastodon GitHub Twitter (inactive)
You are here: Home / Draft / Promise and Async / Await

Promise and Async / Await

Last updated on April 30, 2021 by Sal Ferrarello

Example using a Promise

var getPosts = () => {
    fetch('/wp-json/wp/v2/posts')
        .then((response) => response.json())
        .then((json) => { console.log(json); });
};

Example using async / await

Note: await only works when inside an async function.

var getPosts = async () => {
    var response = await fetch('/wp-json/wp/v2/posts');
    var json = await response.json()
    console.log(json);
};

Equivalent Functions

These two functions are equivalent.

async function exampleAsync() {
  return 'Tada';
}

function examplePromise() {
  return new Promise((resolve) => resolve('Tada'));
}

Both can be called (from within an async function) using the await keyword.

async function runMe() {
  console.log(await exampleAsync());
  console.log(await examplePromise());
};
runMe();

Or both can be called with a .then() method on the response.

exampleAsync().then(value => console.log(value));
examplePromise().then(value => console.log(value));
Sal Ferrarello
Sal Ferrarello (@salcode)
Sal is a PHP developer with a focus on the WordPress platform. He is a conference speaker with a background including Piano Player, Radio DJ, Magician/Juggler, Beach Photographer, and High School Math Teacher. Sal can be found professionally at WebDevStudios, where he works as a senior backend engineer.

Share this post:

Share on TwitterShare on FacebookShare on LinkedInShare on EmailShare on Reddit
Warning! This is a draft, not a finalized post. See full draft disclosure.

Filed Under: Draft, Programming Tagged With: JavaScript, JS async / await, JS Promise

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2023 · Bootstrap4 Genesis on Genesis Framework · WordPress · Log in