简体   繁体   English

在TypeScript中,如何在类构造函数中使用外部函数并从回调中获取值并分配给属性

[英]In TypeScript, How can I use a external function in a class constructor function and get value from callback and assign to a property

How can I assign "aaa" to a??I can't write getStr() in this class because it form a library 我如何为a分配“ aaa”?我不能在此类中编写getStr(),因为它形成了一个库

class a {
    aaa: String
    constructor(aaa) {
        getStr(function(str) {
            // this.aaa = str
        })
    }
}

function getStr(callback) {
    callback("aaa")
}

If you have callback I assume we are talking about async execution. 如果您有回调,我假设我们正在谈论异步执行。 In this case the answer is 在这种情况下,答案是

You cannot 你不能

By definition constructor must return instance of the constructed class. 根据定义,构造函数必须返回所构造类的实例。 This is important. 这个很重要。 Not a Promise<MyClass> , not a Promise<void> . 不是Promise<MyClass> ,不是Promise<void> Therefore what you are trying to archive is not possible. 因此,您尝试存档的内容是不可能的。

Please do not follow the illusion that you can call async function in constructor and it will do the work. 请不要幻想您可以在构造函数中调用异步函数,它会完成工作。 It will be finished sometime after constructor code is finished executing, or maybe not - depending on other code that gets executed alongside. 它会在构造函数代码执行完毕后的某个时候完成,或者可能不会完成-取决于同时执行的其他代码。 This uncertainty - makes this approach extremely dangerous and unpredictable. 这种不确定性-使得这种方法极其危险且不可预测。

What you can do - usually if you need to perform some initialization of the instance that requires async calls - you create a separate init(): promise<void> function that can be correctly called and awaited. 您可以执行的操作-通常在需要执行需要异步调用的实例的初始化时-创建一个单独的init(): promise<void>函数,可以正确地调用它并等待它。

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

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