【发布时间】:2019-08-25 07:47:12
【问题描述】:
我目前正在尝试创建一个从公共交通 API 获取信息的小应用。我创建了一些类来表示对象,其中一些(这里,Route)包含异步方法。
我不知道如何正确调用它们并不断收到 TypeError。
这是我的测试脚本:
import { TagHelper } from './modules/TagHelper';
function testMod() {
TagHelper.getRouteInfo("C1")
.then(C1 => C1.loadPatterns())
.then(C1 => C1.loadStops())
.then(C1 => console.log(C1))
;
}
testMod();
这是我的辅助模块:
import requestPromise = require('request-promise');
class Route {
readonly id: string;
readonly shortName: string;
readonly longName: string;
readonly mode: string;
readonly color: number;
readonly agencyName: string;
patterns: Pattern[];
stops: Stop[];
constructor(id: string, shortName: string, longName: string, mode: string, color: string, agencyName: string) {
this.id = id;
this.shortName = shortName;
this.longName = longName;
this.mode = mode;
this.color = parseInt(color, 16);
this.agencyName = agencyName;
}
async loadPatterns() {
console.log("TEST");
this.patterns = JSON.parse(await requestPromise("https://data.metromobilite.fr/otp/routers/default/index/routes/" + this.id + "/patterns"));
return this;
}
async loadStops() {
this.stops = JSON.parse(await requestPromise("https://data.metromobilite.fr/otp/routers/default/index/routes/" + this.id + "/stops"));
return this;
}
}
class Pattern {
...
}
class Stop {
...
}
const TagHelper = {
getRouteInfo: async function(route_short_name: string, route_mode: string = null): Promise<Route> {
const routes_data: Route[] = JSON.parse(await requestPromise("https://data.metromobilite.fr/otp/routers/default/index/routes"));
for(let route of routes_data) {
if (route.shortName.toUpperCase() === route_short_name.toUpperCase() && (route_mode === null || route_mode.toUpperCase() === route.mode.toLocaleUpperCase()))
return route;
}
return null;
}
};
export { TagHelper, Route, Pattern, Stop };
编辑:我刚刚意识到我没有包含错误,所以这里是:
(node:868) UnhandledPromiseRejectionWarning: TypeError: C1.loadPatterns is not a function
at temp.ts:5:24
【问题讨论】:
-
routes_data不是Route的数组。您没有 Route 类的实例。
标签: node.js typescript promise