首页 > 解决方案 > 等待后承诺解决,但数据未定义

问题描述

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 之外的其他状态代码?

标签: javascriptpromiseasync-awaitrequest-promise

解决方案


我需要使用反序列化从服务返回的 JSON 字符串

  var todo = JSON.parse(response);

出于某种原因,我假设

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

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

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

推荐阅读