[英]Promise resolves after awaited but data is undefined
JavaScript gurus, what am I missing here? JavaScript 大师,我在这里错过了什么?
Simple test scenario as follows:简单的测试场景如下:
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);
}
}
With accompanying Jest test as follows:随附 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);
});
When I run the test, I see the data being returned from the service as当我运行测试时,我看到从服务返回的数据为
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
But if I attempt to access a property of the data such as "userId" I get undefined.但是,如果我尝试访问诸如“userId”之类的数据属性,则会出现未定义的情况。 What am I missing?
我错过了什么?
Also, how do I get other status codes besides a 200 from this request?另外,除了这个请求中的 200 之外,我如何获得其他状态代码?
I needed to deserialize the JSON string returned from the service using我需要使用反序列化从服务返回的 JSON 字符串
var todo = JSON.parse(response);
For some reason, I was assuming that the response to出于某种原因,我假设响应
let response = await request.get("https://jsonplaceholder.typicode.com/todos/1");
was an object but the underlying type is a string .是一个对象,但底层类型是一个string 。 I found this out with the following code:
我用以下代码发现了这一点:
let propertyNames = Object.keys(response);
console.debug(propertyNames);
propertyNames.forEach((p, i) => {
console.debug(response[p])
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.