Search code examples
javascriptecmascript-6

How do I export await multiple objects in javascript?


There's an example in MDN here,

const colors = fetch("../data/colors.json").then((response) => response.json());

export default await colors;

However, I have multiple constants that are populated asynchronously in a single function:

const _receiversById = {}; 
const _receiversByServer = {}; 
const _sequenceReceivers = {}; // name - k-v receivers
const _sequences = {}; 

// init
async function _fetchAllReceivers(){
    // go to the database and copy data into those consts. multiple awaits.
}

I'm puzzled how do I make the constants the promises that get resolved while the function runs.

I was trying to assign the constants to the promise objects without parameters

const _receiversById = new Promise(); 
const _receiversByServer = new Promise(); 
const _sequenceReceivers = new Promise();
const _sequences = new Promise();

thinking to call .resolve(_receivers...) within the _fetch.. function here and there but I highly doubt it will work and will be easy to debug.

What would be the correct/elegant way to achieve this?


Solution

  • Design _fetchAllReceivers so that it returns the four objects you have populated asynchronously. In other words, make the promise returned by _fetchAllReceivers() resolve to the four objects (nested inside a wrapper object).

    async function _fetchAllReceivers(){
        // Make these constants local to the async function
        const receiversById = {}; 
        const receiversByServer = {}; 
        const sequenceReceivers = {}; // name - k-v receivers
        const sequences = {}; 
        // go to the database and copy data into those consts. multiple awaits.
        // ...
        // Return (i.e. resolve with) an object that has all the gathered data
        return {
            receiversById, 
            receiversByServer,
            sequenceReceivers,
            sequences 
        };
    }
    
    export const {
            receiversById, 
            receiversByServer,
            sequenceReceivers,
            sequences 
        } = await _fetchAllReceivers();
    

    On the importing side, you can then do:

    import * as obj from './mymodule.mjs'; 
    console.log(obj.receiversById);
    

    Or:

    import {
            receiversById, 
            receiversByServer,
            sequenceReceivers,
            sequences 
        } from './mymodule.mjs';
    console.log(receiversById);