【发布时间】:2019-09-10 17:51:39
【问题描述】:
我有一个类的方法应该给我一个 API 的域。 到目前为止,这也有效。但是如果我想用 Node Express 渲染它,我会得到一个 1.2.3 的数组。没有域名。
我认为我的问题在于异步等待?!
这是我的类方法中的一个 sn-p:
class ISPConfig {
constructor(base_url, options) {
this.base_url = base_url;
this.options = options;
}
async _call() {
... // gives me the sessionId
}
async getDataByPrimaryId(ispFunction, param) {
try {
const results = await axios.post(this.base_url + ispFunction, {
session_id: await this._call(),
primary_id: param
});
return await results.data.response;
//console.log(results.data.response);
} catch (err){
console.log(err);
}
}
她是我 app.js 中的一个 sn-p:
const renderHome = (req, res) => {
let domains = [],
message = '';
let a = new ispwrapper.ISPConfig(BASE_URL, OPTIONS)
a.getDataByPrimaryId('sites_web_domain_get', { active: 'y' })
.then(response => {
for (let i = 0; i < response.length; i++){
domains = response[i]['domain'].domains;
}
})
.catch(err => {
message = 'Error when retriving domains from ISPApi';
})
.then(() => {
res.render('home', { // 'home' template file for output render
title: 'ISPConfig',
heading: 'Welcome to my ISPConfig Dashboard',
homeActive: true,
domains,
message
});
});
};
使用 push(domains) 我只能访问 HTML 页面 1.2.3。
这与我的 API 的三个活动域完全对应。但只是没有域名。 :(
但如果我在 for loop console.log(response[i]['domain'].domains) 中输出,我会在控制台中获得所有具有名称的域。
有人看到我的错误吗?
这是我的解决方案:
const renderHome = async (req, res) => {
let domain = [],
message = '';
try {
let a = new ispwrapper.ISPConfig(BASE_URL, OPTIONS);
const response = await a.getDataByPrimaryId('sites_web_domain_get', { active: 'y' });
for (let i = 0; i < response.length; i++){
domain.push(response[i].domain);
}
} catch(err) {
message = 'Error when retriving domains from ISPApi';
} finally {
res.render('home', { // 'home' template file for output render
title: 'ISPConfig',
heading: 'Welcome to my ISPConfig Dashboard',
homeActive: true,
domain,
message
});
}
};
【问题讨论】:
标签: javascript node.js express promise async-await