承诺在等待后解决,但数据未定义

时间:2020-03-16 21:34:19

标签: javascript promise async-await request-promise

JavaScript专家,我在这里想念什么?

简单的测试场景如下:

   import * as request from "request-promise-native";

   export class Publisher {

        name : string = "IRocking Publisher";

        async publishAsync(): Promise<PublisherResponse> {

              var publisherResponse : PublisherResponse = PublisherResponse.EmptyResponse;

              try {

                    let response = await request.get("https://jsonplaceholder.typicode.com/todos/1");

                    console.debug("Promise has been resolved.  Result is:")
                    console.debug(response)

                    console.debug(response.userId)
                    publisherResponse = new PublisherResponse(file, this.name, true, "");
                  }
                  catch (error) {
                    publisherResponse = new PublisherResponse(file, this.name, false, error);
                 }

                return Promise.resolve<PublisherResponse>(publisherResponse); 
            }
    }

伴随Jest测试如下:

 test('Should publish a valid single document asynchronously', async () => {

      // Arrange

        let sut = new Publisher(); 
        let expectedResponse = new PublisherResponse(documentToPublish, sut.name, true, "");

        // Act
        let actualResponse = await sut.publishAsync(new PublicationContext(), documentToPublish);   

        // Assert
      expect(actualResponse).toEqual(expectedResponse);
      });

运行测试时,我看到从服务返回的数据为

 {
        "userId": 1,
        "id": 1,
        "title": "delectus aut autem",
        "completed": false
      }

但是,如果尝试访问数据的属性(例如“ userId”),则无法定义。我想念什么?

此外,如何从此请求中获取200以外的其他状态代码?

1 个答案:

答案 0 :(得分:0)

我需要使用

反序列化从服务返回的JSON字符串。
  var todo = JSON.parse(response);

出于某种原因,我假设响应

let response = await request.get("https://jsonplaceholder.typicode.com/todos/1");

是一个对象,但基础类型是 string 。我通过以下代码发现了这一点:

   let propertyNames = Object.keys(response);
    console.debug(propertyNames);
    propertyNames.forEach((p, i) => {
              console.debug(response[p])
            })