[英]React.JS = Promise/Fetch API has repetitive code, how can I bundle into its own function
我正在用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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.