[英]How to properly use Promise.all() and then() with async functions?
[英]How to properly resolve and use promise.all()
我正在尝试使用window.fetch并承诺在我有的地方建立一个ajax模式:
我似乎无法使数据流完全正确地通过所有功能,因此我认为我肯定有一些错误。 我想,这大概是在Promise.all(),因为.then()
之前调用已实际完成这样的公用事业在激发response
为空白。
我的代码在下面(还有要点)。 我之前没有使用诺言,所以我可能会犯错……
controller.js
import {fetchHistoryData} from '/service'
function initChart(config = this.defaultConfig){
fetchHistoryData()
.then((response)=> {
buildChart();
}).catch(()=>{
console.error('Could not get data.');
});
}
}
fetchutils.js
function fetchData(url, options = {mode: 'cors'}, formatter = ((data)=>data)){
console.log(url);
return window.fetch(url, options)
.then(status)
.then(formatter)
.then(function(data){
return data;
})
.catch(throwError);
}
service.js
import {fetchData} from './fetchUtils'
export function fetchHistoryData(){
return Promise.all([fetchHistory('set1'), fetchHistory('set2')]);
//.then((result)=>result); ??
}
function fetchHistory(name){
return new Promise((resolve)=>{
const url = createHistoryUrl(name);
resolve (fetchData(url, {mode:'no-cors'}, historyFormatter));
});
}
该代码几乎没有问题,
initChart
函数不返回任何东西, fetchHistory
中的fetchHistory
包装fetchHistory
,不确定为什么 Promise.all
将返回结果数组(即每个承诺一个结果) formatter
方法,但是then链中的next操作在fetchData
没有任何fetchData
, 有效地,您的代码可以简化为:
//controller.js
import {fetchHistoryData} from '/service'
function initChart(config = this.defaultConfig){
return fetchHistoryData()
.then(response=> buildChart())
.catch(()=> console.error('Could not get data.'));
}
//fetchutils.js
function fetchData(url, options = {mode: 'cors'}, formatter = data => data ){
console.log(url);
return window.fetch(url, options)
.then(status)
.then(formatter)
.catch(throwError); // not sure if catch is need here
}
//service.js
import {fetchData} from './fetchUtils'
export function fetchHistoryData(){
return Promise.all(['set1', 'set2'].map(fetchHistory));
//.then((result)=>result); ??
}
function fetchHistory(name){
return fetchData(createHistoryUrl(name), {mode:'no-cors'}, historyFormatter);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.