0

I am working on merge swagger files. I want to pass array like

[ 
  { method: '1', path: '/signIn', handler: funation() {return "abcd"},
  { method: '2', path: '/signOut', handler: funation() {return "123"},
]

I get result as per my need but it was not pass into module.exports, i have check it into another file console after require this file, my code is like

jsonResolve(root, options).then(function (results) {
  const result = results.resolved.paths;
  // console.log(result);
  for (key in result) {
    // console.log('keys', key);
    const apiRoute = key;
    const apiDescription = result[key];
    let controller = apiDescription['x-swagger-router-controller'];
    for (method in apiDescription) {
      // console.log("methods", method);
      let newRoute = {};
      if (method !== 'x-swagger-router-controller') {
        let operationId1 = apiDescription[method].operationId;

        newRoute = {
          method: method,
          path: apiRoute,
          handler: controllers[controller][operationId1](),
        };
        exoprtData.push(newRoute);
      }
    }
  }
  return exoprtData;
})
.then((result) => {
  console.log(result);
  module.exports = result;
})

I had check it result into last then. but not pass into module.exports

my require file code is like,

var ApiRoutes = require("./routes/api");
console.log("ApiRoutes", ApiRoutes);

And here i get result into console like

ApiRoutes {}

Please help me to solve this problem. Thanks in advance

Akib
  • 193
  • 1
  • 2
  • 13

1 Answers1

0

Node.js expects any module to be loaded synchronously - ie. you must assign to module.exports in the current execution loop, otherwise the module's exported content will be a default empty object.

You are assigning to module.exports after you resolve a promise. This will not work - by the time the promise is resolved, Node.js already finished loading your module and cached the exported value (empty object) as the module's contents. You cannot change it by assigning to module.exports now.

To solve this problem, you must either:

  • export a function which returns the array through promise
  • Somehow make it work synchronously (depends on what jsonResolve() does)
  • Assign the actual promise to module.exports
Robert Rossmann
  • 11,931
  • 4
  • 42
  • 73
  • 1
    You can synchronously assign the promise to `module.exports` (instead of the promise's result) – Bergi Aug 23 '17 at 07:29