javascript - 等待后承诺解决,但数据未定义
问题描述
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 之外的其他状态代码?
解决方案
我需要使用反序列化从服务返回的 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])
})
推荐阅读
- r - 我使用 R 运行了一个基本的逻辑回归模型,我计算出的概率永远不会低于 0.5,这对我来说听起来不正确。
- reactjs - React 中受保护的路由
- sql - 如果使用触发器出现相同的名称,如何进行增量?
- barcode - 使用 bwip-js gs1datamatrix 解析 FNC1 字符
- istio - 使用内部签名证书对 JWKS 进行 Istio JWT 验证
- r - 为什么数字没有映射到每一行?
- xamarin - Xamarin 形成 AppIcon.xcassets 导致上传错误。
- python - Keras ValueError:应在输入列表上调用合并层
- python - 如何通过多列的功能对 Pandas 行进行分组
- java - 消息:PrimeFaces 扩展 DocumentViewer 中缺少 PDF