如何正确解析和使用promise.all()

How to properly resolve and use promise.all()

本文关键字:promise all 何正确      更新时间:2023-09-26

我正在尝试使用window.fetch,并承诺在我拥有的地方构建一个ajax模式:

  1. 发起呼叫的控制器
  2. 定义应用程序所需的URL和参数的服务
  3. 提供获取通用函数的实用程序

我似乎无法让数据流完全正确地通过所有函数,所以我认为我一定是有什么地方连接错了。我认为它可能在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);
}