ES6 import/export merge object with async await Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of ES6 import/export merge object with async await without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have two files called config.js and config.json and I want to merge them into one object and export it:

config.json

{
  "c": 3
}

config.js

import fs from "fs";
import fse from "fs-extra";
import watch from "node-watch";

const config = {
  a: 1
  b: 2
}

//check does file exists
if (fs.existsSync('./src/config.json')) {
  //event emitter watch for changes in json
  const watcher = watch('./src/config.json', { recursive: true });
  //if json ready, then validate and merge
  watcher.on('ready', async function() {
    const importConfig = await fse.readJson('./src/config.json');
    //merge both default config from current file and json
    Object.assign(config, importConfig)
    //small validate function which checks that `json` can be merged
    const valid = await validationConfig(config)
    if (valid) {
      logger.info('Settings has been valid and imported successfully.');
    } else {
      process.exit(1);
    }
  });
}


//console.log(settings) a & b exists, but c does not
export { config };

But somehow, even with fs.existsSync export keyword doesn’t wait for code inside if block to end, and ends before. How this problem can be solved?

Answer

The

watcher.on('ready', async function() {

is a callback. The synchronous code below the callback – that is, the export { config } – will run before the callback finishes.

Export a Promise instead, one which resolves to the value of the loaded config:

const config = { a: 1, b: 2 };
export const configProm = !fs.existsSync('./src/config.json')
    ? Promise.resolve(config)
    : new Promise((resolve, reject) => { // <----------------------------
        const watcher = watch('./src/config.json', { recursive: true });
        watcher.on('ready', async function () {
            const importConfig = await fse.readJson('./src/config.json');
            Object.assign(config, importConfig)
            const valid = await validationConfig(config)
            if (valid) {
                logger.info('Settings has been valid and imported successfully.');
                resolve(config); // <----------------------------
            } else {
                process.exit(1);
                reject(); // ??
            }
        });
    });
We are here to answer your question about ES6 import/export merge object with async await - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji