【发布时间】:2018-10-29 11:44:26
【问题描述】:
我正在用 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
}
}
})
}
【问题讨论】:
-
firstFile和secondFile在getFirstFunc和getSecondFunc中的路径完全相同吗? -
@Tony 是的,完全相同的路径!
-
how can I make the arrays global这不是从异步调用返回响应的正确方法 -
另外,为什么函数
async?他们没有awaiting 任何东西,也没有任何东西被退回 -
@CertainPerformance 嗯,我明白了。我真的是 React.js 的新手,并且正在关注使用 async 和 await 调用 JSON API 的在线教程,我只是重用了该代码。但是感谢您提供的提示,这里并不真正需要它。
标签: javascript reactjs optimization promise fetch-api