我有下一个代码结构:
import {socket} from './socket';
class A{
Execute(...args[]){
//logic with Promises
SomeAsyncMethod1().then(fulfilled1);
function fulfilled1(){
SomeAsyncMethod2(args).then(fulfilled2);
}
function fulfilled2(filled_result){
//(1)
}
}
}
class B{
private a_obj: A;
constructor(){
a_obj = new A();
}
Method1(one: string){
a_obj.Execute(one);
}
Method2(one: number, two: any){
a_obj.Execute(one, two);
}
}
Class C{
interface Ids {
[id: string]: any;
}
let instances: Ids = {};
instances["1"] = new B();
instances["W"] = new B();
CallMethod(callerId: string, objectId: string, methodName: string, args: any[])
instances[objectId][methodName](...args);
//(!) (2)
}
}
“(!)”-我想通过filled_result
通过fulfilled2
将clientId
函数中的socket
发送到客户端。但是我如何到达filled_result
?
像这样:
CallMethod(callerId: string, objectId: string, methodName: string, args: any[])
instances[objectId][methodName](...args);
socket.send_results(callerId, filled_result);
}
问题在于,在(1)中我不认识clientId
,在(2)中我不认识filled_result
答案 0 :(得分:0)
我通过添加以requestId
(在Execute
方法中生成)作为键的映射并将其返回给父函数,该函数将clientId
设置为使用返回的键进行映射,解决了这个问题
import {socket} from './socket';
interface IStringMap {
[key: string]: any;
}
const REQUEST_QUEUE: IStringMap = {};
GenerateRequestID() {
return Math.random().toString(36).substr(2, 9);
};
class A{
Execute(...args[]):string {
let req_id = this.GenerateRequestID();
//logic with Promises
SomeAsyncMethod1().then(fulfilled1);
function fulfilled1(){
SomeAsyncMethod2(args).then(fulfilled2);
}
function fulfilled2(filled_result){
socket.send_results(REQUEST_QUEUE[req_id], filled_result);
delete REQUEST_QUEUE[req_id];
}
return req_id;
}
}
class B{
private a_obj: A;
constructor(){
a_obj = new A();
}
Method1(one: string){
return a_obj.Execute(one);
}
Method2(one: number, two: any){
return a_obj.Execute(one, two);
}
}
Class C{
interface Ids {
[id: string]: any;
}
let instances: Ids = {};
instances["1"] = new B();
instances["W"] = new B();
CallMethod(callerId: string, objectId: string, methodName: string, args: any[])
let reqId = instances[objectId][methodName](...args);
REQUEST_QUEUE[reqId] = callerId;
}
}