简体   繁体   English

产生者,诺言和共同收益

[英]generators, promises and co or then-yield

I am writing a nodejs program and need to get some config data during initialization time so i can instantiate a singleton. 我正在编写一个nodejs程序,需要在初始化期间获取一些配置数据,以便我可以实例化一个单例。 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) . 配置数据作为一个承诺返回,这意味着我必须即时初始化事情,而不是在需要的时间初始化,以便我可以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. 我不希望工厂返回thenable-我希望它返回构造函数的新实例。

I have an internal library that gets configuration data and returns a promise. 我有一个内部库来获取配置数据并返回一个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 我正在尝试使用cothen-yield或类似的库,以便我可以将它们看作是同步的(我认为这是这些库的用途,但也许我的理解是有缺陷的),主要是因为我可以返回实例的工厂,不返回与实例解析的promise

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. 通过查看有关此的各种博客文章,我希望factory通过使用then-yield或co可以返回带有正确配置参数的构造函数。 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. async功能的结果将只是Promise。 So you can access the value of the result of an async function only with a then handler. 因此,您只能使用then处理程序才能访问async函数的结果值。

In your case, 就你而言

let factory = require('factory')()

factory.then((consObj) => // use the Constructor object)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM