javascript - 如何在父函数中获得异步结果?打字稿
问题描述
我有下一个代码结构:
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)
}
}
“(!)” - 我想用viafilled_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
解决方案
我通过添加带有requestId
(在Execute
方法中生成的)作为键的映射并将其返回给父函数来解决此问题,该函数将 a 设置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;
}
}
推荐阅读
- javascript - 如何在 React Native Android 中防止从外部键盘(蓝牙扫描仪)按下后退按钮
- r - purrr map:如何使用嵌套的 tibble 列作为函数参数
- python - 如何使用 python 文件系统将文本放在单独的行上?
- python - 遍历数据帧的字典以获取具有选定列的数据帧的子集
- sapui5 - 如何使用 Uploadset 实现挂起的附件?
- sharepoint - 来自 Sharepoint 的访问令牌
- node.js - TypeError:无法读取未定义命令处理程序的属性“集”
- javascript - 如何在 amCharts 中为 lineSeries 设置 startLocation?
- reactjs - 仅在页面加载/刷新时运行功能,而不是在通过路由更改安装应用程序时
- javascript - 在 moment.js 中返回错误的月份日期