React.JS = Promise / Fetch API有重复的代码,我如何捆绑到自己的函数中

时间:2018-05-19 03:04:41

标签: javascript reactjs optimization promise fetch-api

我正在研究React.JS中的一个小程序。我正在使用Promise和Fetch API从多个文本文件中获取内容。我遇到了一个问题 - 我的很多函数都有完全相同的开头部分,它调用API然后将数据保存到数组中。唯一不同的部分是我如何操作每个函数中的数组。我一直试图弄清楚如何将每个函数的第一部分提取到自己的函数中,以避免重复。

但我的问题是,如何使数组全局化,以便我可以在其他函数中访问它们?

这是我的两个功能 - 欢迎任何建议。

App.js

getFirstFunc = async (e) => { 
  Promise.all([
    fetch(firstFile).then(x => x.text()),
    fetch(secondFile).then(x => x.text())
    ]).then(allResponses => {
      let firstArray = allResponses[0];
      let secondArray = allResponses[1];
      let results = []
      for (let i = 0; i < firstArray.length; i++) {
        for (let j = 0; j < secondArray.length; j++ ) {
          // code for first function
          }
        }
      })
    }
  getSecondFunc = async (e) => {
    Promise.all([
    fetch(firstFile).then(x => x.text()),
    fetch(secondFile).then(x => x.text())
    ]).then(allResponses => {
      let firstArray = allResponses[0];
      let secondArray = allResponses[1];
      let results = []
      for (let i = 0; i < firstArray.length; i++) {
        for (let j = 0; j < secondArray.length; j++ ) {
          // code for second function
          }
        }
      })
    }

1 个答案:

答案 0 :(得分:1)

这意味着对于两个promises文件的处理应该是不同的,你可以创建一个函数,它接受一个执行你想要的处理的函数,并返回一个执行promise的函数。这听起来令人困惑,但我不认为这样做的代码太糟糕了。

makeGetFunc = function (processingFunction) {
  return (e) => { 
    Promise.all([
      fetch(firstFile).then(x => x.text()),
      fetch(secondFile).then(x => x.text())
    ]).then(allResponses => {
      let firstArray = allResponses[0];
      let secondArray = allResponses[1];
      let results = []
      for (let i = 0; i < firstArray.length; i++) {
        for (let j = 0; j < secondArray.length; j++ ) {
          processingFunction(firstArray[i], secondArray[j]);
        }
      }
    })
  }
}
getFunc1 = makeGetFunc(function (a, b) {
  // code for first function
});
getFunc2 = makeGetFunc(function (a, b) {
  // code for second function
});

鉴于上面的代码,如果你想让结果可以在promise之外进行访问,以便稍后在脚本中进行进一步处理,你可以在promise之前声明一个变量,修改回调中的变量并解决promise

let results = []; 
Promise.all([
  fetch(firstFile).then(x => x.text()),
  fetch(secondFile).then(x => x.text())
]).then(allResponses => {
  let firstArray = allResponses[0];
  let secondArray = allResponses[1];
  for (let i = 0; i < firstArray.length; i++) {
    for (let j = 0; j < secondArray.length; j++ ) {
      results.push([firstArray[i], secondArray[j]]);
    }
  }
}).resolve()