目前我所拥有的是:
getData(user) {
return this.$q.all({
userInfo: this.$http.get(this.buildUrl('user.getinfo', user)),
userTopArtists: this.$http.get(this.buildUrl('user.gettopartists', user)),
userChart: this.$http.get(this.buildUrl('user.getWeeklyChartList', user))
.then(resp => {
let promises = [];
let data = resp.data.weeklychartlist.chart;
for (let i = data.length - 4; i < data.length; i++) {
promises.push(
this.$http.get(this.buildUrl('user.getWeeklyTrackChart', user) + `&from=${data[i].from}&to=${data[i].to}`)
.then(resp => {
return resp.data.weeklytrackchart.track.length;
})
);
}
return this.$q.all(promises);
})
}).then(resp => {
return resp;
}).catch(err => {
this.$q.reject('Error' + err.status);
})
}
但我认为可能有一种更实用的方法来构建这个 Promise 对象,因为很多代码都在重复。所以我尝试想出一个更好的解决方案:
buildPromiseObj(target) {
const methods = ['getinfo', 'gettopartists', 'getweeklychartlist'];
let obj = {};
for ( let method in methods ) {
obj[`${methods[method]}`] = this.$http.get(this.buildUrl(`${target}.${methods[method]}`, target))
}
}
- 这种方法有意义吗?我应该使用它吗?
- 您可以看到我在第一个函数中发出的第三个请求还有其他嵌套请求。有什么方法可以将其集成到我上面编写的方法中吗?
最佳答案
是的,像这样概括总是一个好主意。但是:
- Don't use
for…in
enumerations on arrays! `${methods[method]}`
毫无意义地使用模板字符串- 您的方法/属性名称大小写和前缀不一致(
user...
与get...
) - Drop the pointless
.then(resp => { return resp; })
! - 您的
catch
回调不会执行任何操作。它至少应该返回
被拒绝的promise - 或者简单地抛出
错误。另外you should not reject with strings .
关于图表列表,您只需在调用 all
之前将另一个 then
附加到 Promise 中即可。您还可以通过使用更实用的方法来极大地简化回调:
getData(user) {
const methods = ['Info', 'TopArtists', 'WeeklyChartList'];
let promises = {};
for (let method of methods) {
obj['user' + method] = this.$http.get(this.buildUrl('user.get'+method.toLowerCase(), target));
}
promises.userWeeklyChartList = promises.userWeeklyChartList.then(resp =>
this.$q.all(resp.data.weeklychartlist.chart.slice(-4).map(val =>
this.$http.get(this.buildUrl('user.getWeeklyTrackChart', user) + `&from=${val.from}&to=${val.to}`)
).then(resp =>
resp.data.weeklytrackchart.track.length
))
);
return this.$q.all(promises).catch(err => {
throw new Error(err.status);
});
}
关于javascript - 构建 Promise 对象的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47309202/