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

Get several JSON files in one function

JSONlink的结构如下:

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

现在我需要获取几个 JSON link 文件,唯一改变的是上面 link 中的 number 部分.假设它的范围是 10 到 40,所以第一个看起来像这样:

www.something.com/link-10-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 自动 links 它。

谢谢。

概念

  • 生成将从 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)
  })

这样试试,

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 来完成

你可以像这样构建数组

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