I am writing a nodejs program and need to get some config data during initialization time so i can instantiate a singleton. The config data comes back as a promise, which means I have to initialise things on the fly, rather than at require time so i can module.exports = () => return new blah(config)
. I dont want a factory to return a thenable - I want it to return a new instance of a constructor.
I have an internal library that gets configuration data and returns a promise. I'm trying to use co
or then-yield
or a similar library so that I can treat things as if they are synchronous (i think this is what these libs are for, but perhaps my understanding is flawed), mostly so I can make a factory that returns an instance, and doesn't return an promise that resolves with the instance
simplified code:
config reader:
var read = function () {
let c = projectConfig.load(); //returns a promise that resolves with config data
return c;
});
module.exports = {read};
factory:
let factory = ty.async(function * factory () {
let cfg = yield configHelper.read();
console.log('config', cfg)
return new Constructor(cfg);
})
module.exports = () => factory()
index:
let factory = require('factory')()
console.log(factory)
When I run the program I get the following output
Promise {
_d: {
p: [Circular],
c: [],
a: undefined,
s: 0,
d: false,
v: { cdn: [Object] },
h: false,
n: false
}
} // this is from the main module
config { /* correct config object data here */ } //this is from factory
looking at various blog posts talking about this, I would expect that by using then-yield or co, factory
should return the Constructor with the correct config params. but it looks like it co or ty is doing nothing, and im getting the yield result.
What have i misunderstood?
What have i misunderstood?
The result of an async
function will be a Promise only. So you can access the value of the result of an async
function only with a then
handler.
In your case,
let factory = require('factory')()
factory.then((consObj) => // use the Constructor object)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.