JavaScript Promises and async/await, with examples
Requests to the REST API, timers, reading a file the user selected: in the browser such work is asynchronous, the result arrives later. Callbacks nested in callbacks were the old way to handle it. Promises represent a future result as an object, and async/await lets you write asynchronous code that reads like normal top-to-bottom code.
Problem: A theme script loads posts from the REST API, sometimes several requests at once, and the nested callbacks and scattered error handling are hard to follow.
Solution: Use fetch(), which returns a Promise, inside an async function with await and one try/catch. Run independent requests in parallel with Promise.all().
A Promise
function wait( ms ) {
return new Promise( function ( resolve ) {
setTimeout( resolve, ms );
} );
}
wait( 500 ).then( function () {
console.log( 'half a second later' );
} );
A Promise is either pending, fulfilled (with a value) or rejected (with an error). then() runs when it is fulfilled, catch() when it is rejected, and both return a new Promise, so they can be chained.
fetch() with then()
fetch( '/wp-json/wp/v2/posts?per_page=3' )
.then( function ( response ) {
if ( ! response.ok ) {
throw new Error( 'HTTP ' + response.status );
}
return response.json();
} )
.then( function ( posts ) {
posts.forEach( function ( post ) { console.log( post.title.rendered ); } );
} )
.catch( function ( error ) {
console.error( 'Loading posts failed:', error );
} );
fetch() rejects only on network errors. A 404 or 500 is a successful request with response.ok === false, which is why the check is needed.
The same with async/await
async function loadPosts() {
try {
const response = await fetch( '/wp-json/wp/v2/posts?per_page=3' );
if ( ! response.ok ) {
throw new Error( 'HTTP ' + response.status );
}
const posts = await response.json();
posts.forEach( ( post ) => console.log( post.title.rendered ) );
} catch ( error ) {
console.error( 'Loading posts failed:', error );
}
}
loadPosts();
await pauses the function until the Promise settles and returns its value, or throws its error into the catch. The function itself returns a Promise.
Parallel requests
async function loadDashboard() {
const [ posts, pages ] = await Promise.all( [
fetch( '/wp-json/wp/v2/posts?per_page=5' ).then( ( r ) => r.json() ),
fetch( '/wp-json/wp/v2/pages?per_page=5' ).then( ( r ) => r.json() )
] );
console.log( posts.length, pages.length );
}
Two await lines one after the other would wait for the first request before starting the second. Promise.all() starts both at once and fails as soon as one of them fails; Promise.allSettled() waits for all and reports each result separately, which is better when one failed request should not hide the others.
Loops
async function loadThree() {
// Sequential: one request after another
for ( const id of [ 1, 2, 3 ] ) {
const post = await fetch( '/wp-json/wp/v2/posts/' + id ).then( ( r ) => r.json() );
console.log( post.id );
}
// Parallel: all at once
const all = await Promise.all( [ 1, 2, 3 ].map( ( id ) => fetch( '/wp-json/wp/v2/posts/' + id ).then( ( r ) => r.json() ) ) );
console.log( all.length );
}
forEach with an async callback does not wait at all: the loop finishes immediately and the requests run unobserved. Use for...of for sequential work and map with Promise.all() for parallel work.
NOTE: await works only inside async functions (and at the top level of ES modules). And always handle errors: an unhandled rejected Promise only leaves a line in the console, while the user sees a spinner that never stops.