ES2024 JavaScript: Object.groupBy, Promise.withResolvers, and Array.fromAsync

ES2024 in WordPress scripts: Object.groupBy and Promise.withResolvers

ECMAScript 2024 is a small edition, but two of its additions remove boilerplate that almost every admin script has: grouping an array with reduce() and capturing the resolve function of a promise in an outer variable. A third helper, Array.fromAsync(), is not part of ES2024 yet, but it is already in all current browsers and fits well with paginated REST requests.

Problem: An admin tool loads posts from the REST API, groups them by status with a reduce() that nobody wants to read twice, wraps a media frame in a promise with the let resolve; pattern, and collects paginated results in a manual loop.

Solution: Use Object.groupBy() or Map.groupBy() for grouping, Promise.withResolvers() for promises that are resolved from callbacks, and Array.fromAsync() with an async generator for paginated requests, and check the browser support of the admin users before shipping without a build step.

Object.groupBy and Map.groupBy

async function haGroupPosts() {
    const posts = await ( await fetch( '/wp-json/wp/v2/posts?per_page=100&status=any&context=edit&_fields=id,title,status', {
        headers: { 'X-WP-Nonce': wpApiSettings.nonce },
    } ) ).json();

    // before
    const byStatusOld = posts.reduce( ( groups, post ) => {
        ( groups[ post.status ] ??= [] ).push( post );
        return groups;
    }, {} );

    // ES2024
    const byStatus = Object.groupBy( posts, ( post ) => post.status );
    console.log( byStatus.draft?.length ?? 0 );

    // keys that are not strings: Map.groupBy
    const byLength = Map.groupBy( posts, ( post ) => post.title.raw.length > 60 );
    console.log( byLength.get( true ) ); // long titles
}

The callback returns the group key for each element. Object.groupBy() converts keys to strings; Map.groupBy() keeps them as they are (booleans, numbers, objects). The status=any request with context=edit needs a logged-in user and the REST nonce, which wpApiSettings provides when the script depends on wp-api.

The result of Object.groupBy() has a null prototype: byStatus.hasOwnProperty( 'draft' ) throws, because the method does not exist on it. Use Object.hasOwn( byStatus, 'draft' ) or 'draft' in byStatus.

Promise.withResolvers

function haPickImage() {
    const { promise, resolve, reject } = Promise.withResolvers();

    const frame = wp.media( {
        title: 'Choose an image',
        library: { type: 'image' },
        multiple: false,
    } );
    frame.on( 'select', () => resolve( frame.state().get( 'selection' ).first().toJSON() ) );
    frame.on( 'close', () => setTimeout( () => reject( new Error( 'cancelled' ) ), 0 ) );
    frame.open();

    return promise;
}

document.querySelector( '#ha-pick' ).addEventListener( 'click', async () => {
    try {
        const image = await haPickImage();
        document.querySelector( '#ha-image-id' ).value = image.id;
    } catch {
        // the user closed the frame
    }
} );

Before ES2024 the same needed let resolve, reject; const promise = new Promise( ( res, rej ) => { resolve = res; reject = rej; } );. The media frame fires close also after select; the setTimeout lets select resolve first, and a later reject() on a settled promise does nothing. The page needs wp_enqueue_media() in PHP.

Array.fromAsync with paginated requests

async function* haAllPosts( type = 'posts' ) {
    for ( let page = 1; ; page++ ) {
        const response = await fetch( `/wp-json/wp/v2/${ type }?per_page=100&page=${ page }&_fields=id,slug` );
        if ( ! response.ok ) return;
        yield* await response.json();
        if ( page >= Number( response.headers.get( 'X-WP-TotalPages' ) ) ) return;
    }
}

async function haCollectSlugs() {
    const slugs = await Array.fromAsync( haAllPosts( 'pages' ), ( page ) => page.slug );
    console.log( slugs.length );
}

The generator yields posts page by page; Array.fromAsync() collects them into one array, the optional second argument maps each element. X-WP-TotalPages stops the loop without an extra request for an empty page. More about async generators and for await: promises and async/await.

NOTE: Support: Object.groupBy() and Map.groupBy() in Chrome 117, Firefox 119, Safari 17.4; Promise.withResolvers() in Chrome 119, Firefox 121, Safari 17.4; Array.fromAsync() in Chrome 121, Firefox 115, Safari 16.4. Safari 17.4 is from March 2024, so in mid-2024 an admin script without a build step should still check typeof Object.groupBy === 'function' or use a polyfill (core-js has all three). With @wordpress/scripts, Babel does not add these methods by itself; the polyfill has to be imported.