gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:50:54 25 4
gpt4 key购买 nike

我正在使用 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
}
}
})
}

最佳答案

这意味着两个 Promise 的文件处理应该不同,您可以创建一个函数,该函数接受一个函数来执行您想要完成的处理,并返回一个执行 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()

关于javascript - React.JS = Promise/Fetch API 有重复代码,我如何捆绑到它自己的函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50421384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com