admin管理员组

文章数量:1353343

I would like to export a class which initial state depends on a value returned from a Promise in another module i cannot modify.

Here's the code:

let e = true;

APromiseFromAnotherModule()
  .then(value => return value;);

export default class E {
  constructor() {
    if (e) {
      //...
    } else {
      //...
    }
  }
}

I also tried with async/await encapsulating the Promise into an async function like this:

let e = true;

getInitialValue = async () => {
  return await APromiseFromAnotherModule()
    .then(value => e = value;);
};

e = getInitialValue();

export default class E {
  constructor() {
    if (e) {
      //...
    } else {
      //...
    }
  }
}

But it doesn't make sense because that one is an async function so obviously it doesn't work.

What am I missing?

I would like to export a class which initial state depends on a value returned from a Promise in another module i cannot modify.

Here's the code:

let e = true;

APromiseFromAnotherModule()
  .then(value => return value;);

export default class E {
  constructor() {
    if (e) {
      //...
    } else {
      //...
    }
  }
}

I also tried with async/await encapsulating the Promise into an async function like this:

let e = true;

getInitialValue = async () => {
  return await APromiseFromAnotherModule()
    .then(value => e = value;);
};

e = getInitialValue();

export default class E {
  constructor() {
    if (e) {
      //...
    } else {
      //...
    }
  }
}

But it doesn't make sense because that one is an async function so obviously it doesn't work.

What am I missing?

Share Improve this question edited Mar 2, 2018 at 16:17 Ashed asked Mar 2, 2018 at 16:12 AshedAshed 531 silver badge4 bronze badges 4
  • As far as i know export is synchronously. (but you could change properties of it async. And a constructor is also sync. – Roland Starke Commented Mar 2, 2018 at 16:14
  • You are assigning e twice here, why? Once in the return from the async and then the setting to the return of getInitialValue() – wmash Commented Mar 2, 2018 at 16:15
  • +1, export is synchronous. Besides, it's a really bad practice to export an instance of the class. You should export the class and delegate the async stuff to the instantiation, which should happen in the file where the class is imported – Alberto Schiabel Commented Mar 2, 2018 at 16:16
  • @wmash yes you are right, but anyway it doesn't work! – Ashed Commented Mar 2, 2018 at 16:16
Add a ment  | 

2 Answers 2

Reset to default 8

module exports are done synchronously. So, they cannot depend upon the results of an asynchronous operation.

And, await only works inside a function. It doesn't actually block the containing function (the containing function returns a promise) so that won't help you make an async operation into a synchronous one either.

The usual ways to deal with a module that uses some async code in its setup is to either export a promise and have the calling code use .then() on the promise or to initialize the module with a constructor function that returns a promise.

The code is only pseudo code so it's hard to tell exactly what your real problem is to show you specific code for your situation.

As an example. If you want to export a class definition, but don't want the class definition used until some async code has pleted, you can do something like this:

// do async initialization and keep promise
let e;
const p = APromiseFromAnotherModule().then(val => e = val);

class E {
    constructor() {
        if (e) {
            //...
        } else {
            //...
        }
    }
};

// export constructor function
export default function() {
   return p.then(e => {
       // after async initialization is done, resolve with class E
       return E;
   });
}

The caller could then use it like this:

import init from 'myModule';
init().then(E => {
   // put code here that uses E
}).catch(err => {
   console.log(err);
   // handle error here
});

This solves several issues:

  1. Asynchronous initialization is started immediately upon module loading.
  2. class E is not made available to the caller until the async initialization is done so it can't be used until its ready
  3. The same class E is used for all users of the module
  4. The async initialization is cached so it's only done once

Edit in 2023. Modern nodejs versions when using ESM modules have top level await so it is possible to await an asynchronous result before your exports.

I understand that @jfriend00's answer works fine, but in my case, there is not just one block of code that depends on the foreign async function's pletion.

In my app, configuration loading is asynchronous, so the server must wait for the configs to load before starting. Since there are other files (like routes) that pose the server that also need access to the configs, I would have to reluctantly call .then() in each other file.

Here is how I was able to do it with require statements instead of export.

config.js

Module that can be required by other modules in order to gain access to the global configs.

module.exports.loadAllConfigs = async () => {
  const appConfigs = await AsyncConfigLibrary.load();
  module.exports.CONFIG = appConfigs;
};

server.js

Main file for Node application that makes use of other modules that require access to global configs.

const { loadAllConfigs } = require('./modules/config');

loadAllConfigs()
  .then(() => {
    const { CONFIG } = require('./modules/config');

    /* import modules */
    const auth = require('./modules/auth');
};

auth.js

Module used by server.js that requires access to configs.

const { CONFIG } = require('./config');
const cookieSecret = CONFIG.secretItem;

Therefore, as long as the CONFIG property is set in config.js before any of the other modules attempt to access it, that is, before the modules are require'd, then the single .then() in server.js is sufficient.

本文标签: javascriptexporting after promise finishesStack Overflow