我目前正在尝试创建一个小型应用,该应用从公共交通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
答案 0 :(得分:0)
事实证明,我只是混淆了JSON对象和类实例。感谢estus指出了这一点!
我通过修改Route
类来纠正我的错误:
class Route {
...
patterns: Pattern[];
stops: Stop[];
constructor(id: string, shortName: string, longName: string, mode: string, color: string, agencyName: string) {
...
this.patterns = [];
this.stops = [];
}
async loadPatterns() {
for (let pattern of JSON.parse(await requestPromise("https://data.metromobilite.fr/otp/routers/default/index/routes/" + this.id + "/patterns"))) {
this.patterns.push(new Pattern(pattern.id, pattern.desc));
}
return this;
}
async loadStops() {
for (let stop of JSON.parse(await requestPromise("https://data.metromobilite.fr/otp/routers/default/index/routes/" + this.id + "/stops"))) {
this.stops.push(new Stop(stop.bind, stop.code, stop.name, stop.lat, stop.lon, stop.cluster));
}
return this;
}
}