gpt4 book ai didi

javascript - Node.js 中的面向对象设计

转载 作者:搜寻专家 更新时间:2023-10-31 23:49:24 25 4
gpt4 key购买 nike

我正在为 Node.jsasync 流程而苦苦挣扎。假设您有以下类(class):

function myClass() {
var property = 'something';
var hasConnected = false;

this.connect = function(params) {
//Some logic that connects to db and in callback returns if the connection is successful
connectToSomeDB('ConnectionString', function(connectionResult) {
hasConnected = connectionResult
})
};

this.get = function(params) {
if(hasConnected) {
DoGetOperation() //
}
else {
//Another question. What should be done here. Call the connect again?
}
}
}

考虑到 Javascript 和 Node 结构,我当然认为我的设计存在一些主要问题,但我无法找到解决办法,因为 connect 必须调用 才能进行任何操作运行才能正常工作。但是当我在操作后进行一些日志记录时:

brandNewObject = myClass();
brandNewObject.connect();
brandNewObject.get();

我观察到在获取全局 isConnected 变量之前调用了 get 函数。我该怎么做才能在不违背 Node 的异步结构的情况下完成这项工作?

理想情况下,我正在寻找的解决方案实际上是在内部处理“连接”,而不是定义回调“外部类”

最佳答案

对此有不同的解决方法。

一种简单的方法与您正在做的类似

this.get = function(params) {
if (hasConnected) {
DoGetOperation(params);
} else {
//here you can check the status of the connect. if it is still in
//progress do nothing. if the connection has failed for some reason
//you can retry it. Otherwise send a response back indicating that the
//operation is in progress.
}
}

另一种方法可能是对您的 get 函数使用相同的异步回调机制,这会将您的方法签名更改为类似这样的内容。

this.deferredOperations = new Array();

this.get = function(params, callback) {
if (hasConnected) {
//using a callback as an optional parameter makes the least
//impact on your current function signature.
//If a callback is present send the data back through it,
//otherwise this function simply returns the value (acts synchronously).
if (callback !== null) {
callback(DoGetOperation(params));
} else {
return DoGetOperation(params);
}
} else {
this.deferredOperations.push([params,callback]);
}
}

//connect changes now
this.connect = function(params) {
//Some logic that connects to db and in callback returns if the connection is successful
connectToSomeDB('ConnectionString', function(connectionResult) {
hasConnected = connectionResult;
if (hasConnected && this.deferredOperations.length > 0) {
for (var i=0; i < this.deferredOperations.length; i++) {
var paramFunction = this.deferredOperations.pop();
var params = paramFunction[0];
var func = paramFunction[1];
DoAsyncGetOperation(params, func); //Need to write a new function that accepts a callback
}
}
})
};

HTH

关于javascript - Node.js 中的面向对象设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14355709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com