反应.JS = 承诺/获取 API 有重复的代码,我怎么能捆绑到它自己的函数中



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

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

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

应用.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
}
}
})
}

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

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()

相关内容

最新更新