[英]How to get async result in parent function? TypeScript
I have next code structure: 我有下一个代码结构:
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)
}
}
"(!)" - There I want to send filled_result
from fulfilled2
function to client with clientId
via socket
. “(!)” -在那里,我想送
filled_result
从fulfilled2
功能,客户端clientId
通过socket
。 But how I can get there filled_result
? 但是我怎么能到达
filled_result
呢? Like this: 像这样:
CallMethod(callerId: string, objectId: string, methodName: string, args: any[])
instances[objectId][methodName](...args);
socket.send_results(callerId, filled_result);
}
The problem is that in (1) I don't know clientId
, in (2) I dont know filled_result
问题是在(1)中我不知道
clientId
,在(2)中我不知道filled_result
I resolved this issue by adding map with requestId
(generated in Execute
method) as key and return it to parent function which set a clientId
to map with returned key 我通过添加具有
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.