如何正确解析和使用promise.all()
How to properly resolve and use promise.all()
我正在尝试使用window.fetch,并承诺在我拥有的地方构建一个ajax模式:
- 发起呼叫的控制器
- 定义应用程序所需的URL和参数的服务
- 提供获取通用函数的实用程序
我似乎无法让数据流完全正确地通过所有函数,所以我认为我一定是有什么地方连接错了。我认为它可能在Promise.all()中,因为实用程序中的.then()
在调用实际完成之前就启动了,所以response
为空。
我的代码如下(还有要点)。我以前很少使用承诺,所以我可能会犯错误。。。
控制器.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);
}
services.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));
});
}
https://gist.github.com/thedamon/86601ba009bfd05cb791
这个代码很少有问题,
- CCD_ 3函数不返回任何内容
- 你在
fetchHistory
中用承诺包装承诺,不知道为什么 - 如果您想知道,
Promise.all
将返回一组结果(即每个承诺一个结果) - 我可以理解默认的
formatter
方法,但然后链中的下一个操作在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);
}
相关文章:
- 如何在异步函数中正确使用Promise.all()和then()
- promise.all在一个forEach循环中——所有东西都同时启动
- 如何将Promise.all与其他Promise.all
- 运行Promise.all()中的When-is-then-then子句
- Promise和Promise.all(数组)在数组实现之前执行
- promise.all只返回第一个数据
- Node.js中的Promise.all没有't调用then函数
- Promise.all()方法没有't解析为一个值
- 如何正确解析和使用promise.all()
- Promise.all() - 在触发多个事件侦听器后执行某些操作
- 为什么 Promise.all(array) 没有立即解决
- Promise.all:解析值的顺序
- RXJS5 vs Promise.all
- 对象文字(哈希)与 Promise.all
- ES6 Promise.all() promise 数组的奇怪分辨率
- Promise.all behavior with RxJS Observables?
- Promise.all() - 如何在不返回 undefined 或 value 的情况下解析()
- 为什么在 Promise.all() 之后没有调用 onJect,其中数组中包含的 Promise.reject() 传
- Promise.all 不应该作为传递给 .then 的函数工作
- Promise.all() 解析,但它不应该(node.js)