繁体   English   中英

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

[英]How to properly resolve and use promise.all()

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

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

我似乎无法使数据流完全正确地通过所有功能,因此我认为我肯定有一些错误。 我想,这大概是在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));
    });
}

https://gist.github.com/thedamon/86601ba009bfd05cb791

该代码几乎没有问题,

  • 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM