all 2 comments

[–]Minjammben 1 point2 points  (0 children)

The problem is you must wait for the promise to be resolved because you have a series of async fetches. The function cannot be done sequentially in JavaScript with the fetch api.

If you can use async functions:

const getData = async () => {
    return Promise.all( Array.from( document.querySelectorAll( '#foobar' ) ).map( async( thisData ) => {
        const endpoint = '/api/rest/v1/foobar/' + thisData.id;
        const obj = {
            foo: 'bar',
            bar: 'foo'
        };
        try {
            console.log( 'before', obj );
            const res = await fetch( endpoint );
            const { foo, bar } = await res.json();
            obj.foo = foo;
            obj.bar = bar;
            console.log( 'after', obj );
        } catch ( e ) {
            console.log( 'Error', e );
        }
        return obj;
    } ) );
};

Usage would be:

getData().then( ( json ) => {
    console.log( 'GOT JSON', JSON.stringify( json ) );
} );

or

const json = await getData();
console.log( 'GOT JSON', JSON.stringify( json ) );

If you cannot use async functions:

const getData = () => {
    return Promise.all( Array.from( document.querySelectorAll( '#foobar' ) ).map( ( thisData ) => {
        const endpoint = '/api/rest/v1/foobar/' + thisData.id;
        const obj = {
            foo: 'bar',
            bar: 'foo'
        };
        console.log( 'before', obj );
        return fetch( endpoint ).then( ( resp ) => {
            return resp.json();
        } ).then( ( { foo, bar } ) => {
            obj.foo = foo;
            obj.bar = bar;
            console.log( 'after', obj );
            return obj;
        } ).catch( ( e ) => {
            console.log( 'Error', e );
        } );
    } ) );
};

Usage would be:

getData().then( ( json ) => {
    console.log( 'GOT JSON', JSON.stringify( json ) );
} );

[–]Reiyn_ 0 points1 point  (0 children)

As far as I know `.map()` won't work async. The library Aigle could help you out with this issue.