1

I need to asynchrounisly get some data during module startup and save returned value as top level variable. And other methods of module should not be called before this variable has been initialized.

So basically I need something like this:

myModule.js
===========

// i can't use await here...
const importantData = await fetch('/my-service'); 

exports.myMethod = function () {
    // do something with importantData
}

So,

  1. Top level importantData is promise

  2. If someone call myMethod method then it should defer it's execution until top level const is resolved

  3. I don't want to use let

What is the elegant way to sove this problem?

Thanks

1
  • Make every exported function an async function that internally awaits the resolution of the initialization fetch. Commented May 28, 2018 at 22:38

1 Answer 1

2

You will need to make myMethod asynchronous:

const importantDataPromise = fetch('/my-service'); 

exports.myMethod = async function () {
    const importantData = await importantDataPromise;
    ... // Do stuff with importantData.
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.