在一个函数中获取多个JSON文件

Get several JSON files in one function

本文关键字:获取 JSON 文件 一个 函数      更新时间:2023-09-26

JSON link的结构如下:

www.something.com/link- -rest-of-the-link.com.json

现在我需要得到几个JSON链接文件,唯一改变的是上面链接中的数字部分。假设它的范围是10到40,那么第一个是这样的:

10

www.something.com/link- -rest-of-the-link.json

第二个是这样的

www.something.com/link- 11 -rest-of-the-link.com.json

等等,直到第40个。

有没有一种方法可以让我在一个函数中得到它。我试过了:

var nmr = function({for(nmr=10;nmr<40;nmr++)});
var json = 'www.something.com/link'+nmr+'rest-of-the-link.json';

但是行不通。

有办法做到这一点吗?

请注意,我没有把"http"部分,因为SO会自动链接它。

谢谢。

你可以像这样构建数组

var links = [];
for(var i=2005;i<2015.length;i++){
  links.push('http://www.link.com/an-'+i+'-rest');
}
//now make your request for each link

另一个例子
var requested = 0;
  function startLoading(){
    if(requested==2015) {
      return alert("all files loaded");
    }
    makeRequest('http://www.link.com/an-'+requested+'-rest');
  }
  function makeRequest(url){
    //the body of request
    //then
    //if response is ready make what you want for it and go next
    requested++;
    startLoading();
    // and startLoading(); to go to the next link
  }
  startLoading(); //start

试一下,

var json = [];
for(var i = 10; i <= 40; i++) {
   json.push('www.something.com/link-'+i+'-rest-of-the-link.json');
}

现在json将具有从10到40的所有链接。如果你想获取内容,使用ajax

概念

  • 生成承诺数组,将从url

  • 调用每个json文件
  • 同时执行每个承诺

const Promise = require('bluebird')
const rp = require('request-promise')
function getJsonFromUrlParam(num) {
  const uri = `www.something.com/link-${num}-rest-of-the-link.json`
  return rp({ method: 'GET', uri, json: true })
}
/** declare param */
const params = []
for (let i = 10; i <= 40; i++) {
  /** get each promise param */
  params.push(getJsonFromUrlParam(i))
}
/** get each json file in the same time */
Promise.all(params)
  .then(result => {
    /** get result here 
     * result is array of json files
     */
     console.log(result)
  })