javascript - How can I make multiple API calls to save all results in one json file using Nodejs? -


i want fetch results json api different urls (values) in 1 go , save results in 1 json file. approach following, stuck pending promises in resulting object , json file. there way can solve using promises, or shall use callbacks? hint appreciated. sure can coded better.

const fetch = require('node-fetch'); const util = require('util');  function getindicator (indicator) {   url = 'http://api.worldbank.org/countries/de/indicators/' + indicator + '/?date=2012:2018&format=json';   let result = fetch(url)     .then(function(res) {       return res.json();     })     .then(function(json) {       return json;     })   return result; }  function loadindicators () {   let indicators = ['sp.pop.totl','sp.dyn.imrt.in','sp.dyn.le00.in'];   let german_indicators = {};   indicators.foreach(function (e) {     german_indicators[e] = getindicator(e);   })   return german_indicators; }  let result = loadindicators(); fs.writefilesync('./data.json', util.inspect(result), 'utf-8'); 

your getindicator , loadindicators function return promise can promise.all in loadindicators loop.

const fetch = require('node-fetch'); const util = require('util'); function getindicator(indicator) {     const url = 'http://api.worldbank.org/countries/de/indicators/' + indicator + '/?date=2012:2018&format=json';     return fetch(url)         .then(function (res) {             return res.json();         }); } function loadindicators() {     return new promise((resolve, reject) => {         const promises = [];         let indicators = [             'sp.pop.totl',             'sp.dyn.imrt.in',             'sp.dyn.le00.in'         ];         let german_indicators = {};         indicators.foreach(function (e) {             promises.push(new promise((resolve, reject) => {                 getindicator(e).then((result) => {                     german_indicators[e] = result;                     resolve();                 }).catch(reject);             }));         });         promise.all(promises).then(() => {             resolve(german_indicators);         }).catch(reject);     }); } loadindicators().then((result) => {     fs.writefilesync('./data.json', util.inspect(result), 'utf-8'); }).catch(console.error); 

Comments

Popular posts from this blog

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

html - How to custom Bootstrap grid height? -

transpose - Maple isnt executing function but prints function term -