Javascript 如何将async Wait与Promise.all()一起使用?
目前,我正在使用下面的代码使用async await获得几个承诺的结果:Javascript 如何将async Wait与Promise.all()一起使用?,javascript,async-await,Javascript,Async Await,目前,我正在使用下面的代码使用async await获得几个承诺的结果: let matchday = await createMatchday(2018, 21, [/*9 matches of matchday*/]); //Further calculations async function createMatchday(seasonNr, matchdayNr, matches) { let md = new Matchday(seasonNr, matchdayNr, matc
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.all()同时生效,还是有更好的方法,例如,同时生成多个httprequest,因为这看起来很重复?要创建一个新的承诺,您需要调用新的承诺((解析,拒绝)=>{返回“Pizza”;})
你做得对
如果需要,您可以通过使用数组(以及它的函数,如map
,等等)来缩短代码,但它不会提高其性能来创建一个新的承诺,您需要调用新的承诺((resolve,reject)=>{return“Pizza”;})
你做得对
如果你想缩短代码,你可以使用一个数组(以及它的函数,如
map
,等等),但它不会提高它的性能来回答,不,你不应该阻止其他XHR或任何互不依赖的I/O请求
const getfavorites=async()=>{
试一试{
const result=等待承诺。解决(“比萨饼”);
console.log(“最喜欢的食物:+结果”);
}捕获(错误){
console.log(“获取食物时出错”);
}
试一试{
const result=等待承诺。解决(“猴子”);
console.log(“最喜欢的动物:+结果”);
}捕获(错误){
log('error get animal');
}
试一试{
const result=等待承诺。解决(“绿色”);
console.log(“最喜欢的颜色:+结果”);
}捕获(错误){
log(“获取颜色时出错”);
}
试一试{
const result=等待承诺。解决(“水”);
控制台日志(“最喜欢的液体:+结果);
}捕获(错误){
log(“获取液体时出错”);
}
}
getFavorites();
要回答这个问题,不应该阻止其他XHR或任何互不依赖的I/O请求
const getfavorites=async()=>{
试一试{
const result=等待承诺。解决(“比萨饼”);
console.log(“最喜欢的食物:+结果”);
}捕获(错误){
console.log(“获取食物时出错”);
}
试一试{
const result=等待承诺。解决(“猴子”);
console.log(“最喜欢的动物:+结果”);
}捕获(错误){
log('error get animal');
}
试一试{
const result=等待承诺。解决(“绿色”);
console.log(“最喜欢的颜色:+结果”);
}捕获(错误){
log(“获取颜色时出错”);
}
试一试{
const result=等待承诺。解决(“水”);
控制台日志(“最喜欢的液体:+结果);
}捕获(错误){
log(“获取液体时出错”);
}
}
getFavorities();
您的URL都遵循相同的模式,因此您可以通过映射
ping一个['''home','away','form'数组来大大减少代码
到URL。然后,通过makeHttpRequestTo
将这些URL映射到承诺,然后您可以将等待的结果分解为this。
属性:
async getStandings(seasonNr, matchdayNr) {
const urls = ['', 'home', 'away', 'form']
.map(str => `http://externService.com/${str}standings?seasonNr=${seasonNr}&matchdayNr=${matchdayNr}`);
const promiseArr = urls.map(makeHttpRequestTo);
[
this.standings,
this.homeStandings,
this.awayStandings,
this.formStandings
] = await Promise.all(promiseArr);
}
要单独填充每个属性,而不是等待所有响应返回,请执行以下操作:
async getStandings(seasonNr, matchdayNr) {
['', 'home', 'away', 'form']
.forEach((str) => {
const url = `http://externService.com/${str}standings?seasonNr=${seasonNr}&matchdayNr=${matchdayNr}`;
makeHttpRequestTo(url)
.then((resp) => {
this[str + 'Standings'] = resp;
});
});
}
您的URL都遵循相同的模式,因此您可以通过map
ping一个[''home'、'away'、'form'数组来大大减少代码
到URL。然后,通过makeHttpRequestTo
将这些URL映射到承诺,然后您可以将等待的结果分解为this。
属性:
async getStandings(seasonNr, matchdayNr) {
const urls = ['', 'home', 'away', 'form']
.map(str => `http://externService.com/${str}standings?seasonNr=${seasonNr}&matchdayNr=${matchdayNr}`);
const promiseArr = urls.map(makeHttpRequestTo);
[
this.standings,
this.homeStandings,
this.awayStandings,
this.formStandings
] = await Promise.all(promiseArr);
}
要单独填充每个属性,而不是等待所有响应返回,请执行以下操作:
async getStandings(seasonNr, matchdayNr) {
['', 'home', 'away', 'form']
.forEach((str) => {
const url = `http://externService.com/${str}standings?seasonNr=${seasonNr}&matchdayNr=${matchdayNr}`;
makeHttpRequestTo(url)
.then((resp) => {
this[str + 'Standings'] = resp;
});
});
}
如果不希望在继续执行流之前等待所有请求完成,可以将类的属性设置为:
class Matchday {
constructor(seasonNr, matchdayNr, matches) {
this.seasonNr = seasonNr;
this.matchdayNr = matchdayNr;
this.matches = matches;
['standings', 'homeStandings', 'awayStandings', 'formStandings'].forEach(propertyName => {
let url = `http://externService.com/${propertyName.toLowerCase()}`
+ `?seasonNr=${seasonNr}&matchdayNr=${matchdayNr}`
this[propertyName] = makeHttpRequestTo(url)
});
}
}
使用以下代码段进行测试
班级比赛日{
构造函数(季节编号、匹配日期编号、匹配){
this.seasurenr=seasurenr;
this.matchdayNr=matchdayNr;
this.matches=匹配项;
['standings'、'homeStandings'、'awayStandings'、'formStandings'].forEach(propertyName=>{
让url=`http://externService.com/${propertyName.toLowerCase()}`
+`?季候nr=${季候nr}&matchdayNr=${matchdayNr}`
此[propertyName]=makeHttpRequestTo(url)
});
}
}
/**************************************
*测试线束
**************************************/
函数makeHttpRequestTo(url){
//将AJAX httpRequest伪造为url
请求的常量\u resource=url.match('^.*\/\/.\/.\/([^?]*))[1];
const fake_response_data='url.match('^.*\/\/.\/.\/(.*)$')[1]的数据;
设延迟=0;
让反应='';
交换机(请求的\u资源){
//为了让它有趣,让我们提供“排名”资源
//更快的响应时间
案件“排名”:
延迟=250;
打破
“家庭看望”案例:
延迟=2000;
打破
“awaystadings”案例:
延迟=3000;
打破
“表格排名”案例:
延迟=4000;//{
setTimeout(()=>解析(假响应数据),延迟);
});
}
异步函数testAccessingAllProperties(){
const testId=“测试访问所有属性”;
console.log('\n%s',testId);
控制台时间(testId)
让md=新的比赛日(2018,21,[]);
控制台日志(等待md.standings);
控制台日志(等待md.homeStandings);
控制台日志(等待md.awayStations);
控制台日志(等待md.formStandings);
console.timeEnd(testId)
}
异步函数testAccessingOnlyOneProperty(){
const testId=`Test仅访问一个属性`;
console.log('\n%s',testId);
控制台时间(testId)
让md=新的比赛日(2018,21,[]);
控制台日志(等待md.standings);
console.timeEnd(testId)
}
异步函数所有_测试(){
等待testAccessingAllProperties();
等待testAccessingOnlyOneProperty();
}
如果不想在继续执行之前等待所有请求完成,请选择all_tests();