[英]Promise resolves after awaited but data is undefined
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");
是一個對象,但底層類型是一個string 。 我用以下代碼發現了這一點:
let propertyNames = Object.keys(response);
console.debug(propertyNames);
propertyNames.forEach((p, i) => {
console.debug(response[p])
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.