如何在父函数中获取异步结果?打字稿

时间:2019-04-11 14:55:12

标签: javascript typescript

我有下一个代码结构:

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通过fulfilled2clientId函数中的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

1 个答案:

答案 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;
  }
}
相关问题