首页 文章

在Typescript / JavaScript中展开Promise对象

提问于
浏览
4

我是JavaScript / TypeScript Promise返回类型的新手 .

问题是我正在托管一个rest API endpoints ,它在内部调用另一个使用JS Request模块返回Promise对象的服务的API .

我想打开内部API promise响应并创建一个新的普通Typescript对象,最后返回新修改的响应对象而不是Promise .

以下是描述我的问题的示例代码:

export class SampleClass {
 public process(): NewResponse {
    const newResponse: NewResponse = new NewResponse();
    // invokeOtherAPI() call Returns a Promise by invoking a different endpoint
    invokeOtherAPI().then(function (result) {
        newResponse.propertyOne = result.propertyOne;
        newResponse.propertyTwo = result.propertyTwo;
    });
    return newResponse;
}}

在这种情况下,process()返回一个空值,虽然它在then()内部分配 .

这是我的REST API控制器类(缺少路径装饰器)

export class SampleController() {
  const service: SampleClass = new SampleClass();
  public get(): NewResponse {
     return service.process();
  }
}

问题:

  • 从Typescript API一直返回Promise对象是一个好习惯吗?

  • 有没有办法可以在内部解包promise对象并从API返回非promise对象?

感谢您的帮助 .

1 回答

  • 4

    我想解开内部API promise响应并创建一个新的普通Typescript对象,最后返回新修改的响应对象而不是Promise .

    你不能 . 如果您的API函数的任何部分是异步的,那么整个API必须是异步的,这意味着它必须返回一个承诺,调用者使用 .then()await 来获取值,或者您使用旧样式回调和调用者传递一个回调,当异步值可用时,您将调用该回调 .

    这里有更多的解释:How do I return the response from an asynchronous call? .

    从Typescript API一直返回Promise对象是一个好习惯吗?

    是 . 如果操作是异步的,则返回promise是与异步结果进行通信的理想方式 .

    有没有办法在内部解包promise对象并从API返回非promise对象?

    不 . 如果你真的不想使用promises,你可以使用旧的回调样式来回传结果,但是调用者在处理异步结果时会遇到同样的问题,你不能直接从结果返回结果你的API .


    在这段代码中:

    export class SampleClass {
     public process(): NewResponse {
        const newResponse: NewResponse = new NewResponse();
        // invokeOtherAPI() call Returns a Promise by invoking a different endpoint
        invokeOtherAPI().then(function (result) {
            newResponse.propertyOne = result.propertyOne;
            newResponse.propertyTwo = result.propertyTwo;
        });
        return newResponse;
    }}
    

    事情出错了 return newResponse . 那时, newResponse 还没有值 . 您知道它具有值的唯一位置在 .then() 处理程序内 . 这就是为什么你可以't return the result directly from your API. Your API will return BEFORE the value has been retrieved. That'究竟是什么承诺 . 您返回promise并且调用者在返回的promise上使用 .then() 来获取值 .

    我自己不知道TypeScript的方法,所以你可以填写返回值的正确语法,但这是在这里返回的承诺:

    export class SampleClass {
     public process(): <fill in promise return value type here> {
        const newResponse: NewResponse = new NewResponse();
        // return promise from this function
        return invokeOtherAPI().then(function(result) {
            newResponse.propertyOne = result.propertyOne;
            newResponse.propertyTwo = result.propertyTwo;
            // make newResponse be the resolved value of the promise
            return newResponse;
        });
    }};
    

相关问题