如何获取动态数据提供代码

时间:2018-06-12 03:26:45

标签: javascript reactjs react-native dynamic

鉴于我有以下代码从本地文件中获取数据。

export function getData() {
    const promiseMSFT = fetch("http://localhost:8080/data.json")
        .then(response => response.json())
        .then(data => {
        var tempData = [];
        for (var i = 0; i < data.length; i++) {
          //some code
       }
      return tempData;
    })  
    return promiseMSFT;
}

如何将其转换为从不同/动态网址动态获取数据?

示例,如果我生成了这些URL:

url1 with data1
url2 with data2
url3 with data3

我怎样才能得到三个结果。

3 个答案:

答案 0 :(得分:0)

urlArr = [site/test/1/data.json, site/test/2/data.json, site/test/3/data.json]
export function getData(url) {
    const promiseMSFT = fetch(url)
        .then(response => response.json())
        .then(data => {
        var tempData = [];
        for (var i = 0; i < data.length; i++) {
          //some code
       }
      return tempData;
    })  
    return promiseMSFT;
}

urlArr.forEach(url=>{getData("http://"+url)})

答案 1 :(得分:0)

更新@tung yu的答案

export function getData(url) {
    const promiseMSFT = fetch(url)
        .then(response => response.json())
        .then(data => {
        var tempData = [];
        for (var i = 0; i < data.length; i++) {
          //some code
       }
      return tempData;
    })  
    return promiseMSFT;
}

然后执行此操作:

data1 = getData(url1)
data2 = getData(url2)
data3 = getData(url3)
许多网址

var urls = [url1,url2, ....]; 
var dataitems = []; 
for(var i=0;i<urls.length;i++) 
{ 
     dataitems[i] = getData(url[i]);
}

您将在数据项目&#39;中获得最终结果。阵列

答案 2 :(得分:0)

你可以这样做:

export function getData(url) {
 //if you have n urls
let URLS = []
let tempData = [];
for(int i=1;i<=n;i++){
  url = `site/test/${i}/data`
  URLS.push(url);
 }
return Promise.all(
  URLS.map(url => 
    fetch(url)
    .then(response => response.text())
    .then(responseData => {
      //push data to temp data here
    })
    .catch(err => /* handle errors here */ console.error(err))
  )
).then(() => {// do stuff}, err => {// handle error})
}