【发布时间】:2019-02-09 20:04:09
【问题描述】:
目前我正在使用下面的代码来获取使用异步等待的几个 Promise 的结果:
let matchday = await createMatchday(2018, 21, [/*9 matches of matchday*/]);
//Further calculations
async function createMatchday(seasonNr, matchdayNr, matches) {
let md = new Matchday(seasonNr, matchdayNr, matches);
await md.getStandings(seasonNr, matchdayNr);
return md;
}
class Matchday {
constructor(seasonNr, matchdayNr, matches) {
this.seasonNr = seasonNr;
this.matchdayNr = matchdayNr;
this.matches = matches;
}
async getStandings(seasonNr, matchdayNr) {
let promiseArr = [];
promiseArr.push(makeHttpRequestTo(`http://externService.com/standings?seasonNr=${seasonNr}&matchdayNr=${matchdayNr}`);
promiseArr.push(makeHttpRequestTo(`http://externService.com/homestandings?seasonNr=${seasonNr}&matchdayNr=${matchdayNr}`));
promiseArr.push(makeHttpRequestTo(`http://externService.com/awaystandings?seasonNr=${seasonNr}&matchdayNr=${matchdayNr}`));
promiseArr.push(makeHttpRequestTo(`http://externService.com/formstandings?seasonNr=${seasonNr}&matchdayNr=${matchdayNr}`));
let resulArr = await Promise.all(promiseArr);
this.standings = resultArr[0];
this.homeStandings = resultArr[1];
this.awayStandings = resultArr[2];
this.formStandings = resultArr[3];
}
}
function makeHttpRequest(url) {
return new Promise((resolve, reject) => {
//AJAX httpRequest to url
resolve(httpRequest.responseText);
}
}
这实际上是读取多个 Promise 值的最佳方法吗,其中 Promise 不需要等待对方结束,而是使用 Promise.all() 同时工作还是有更好的方法制作例如多个httpRequests,因为这看起来很重复?
【问题讨论】:
-
您当前的代码确实同时发出多个请求(假设
Promise.resolves 被替换为发出请求的东西) -
我只是想知道这是不是这样写的方式,因为它看起来很不方便......
-
你说的“更好”是什么意思?有什么要求?
-
你的意思是代码看起来太重复了?我同意,但是没有看到真实代码,很难说有什么可以改进的
-
添加了“真实”代码...