Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

javascript - exporting after promise finishes

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 completed, 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...