Reputation: 123
get all forEach result out of foreach.
results.forEach(function(data){
var fx = require('../lib/money'),
oxr = require('open-exchange-rates');
// Set App ID (required):
oxr.set({
app_id: 'd5e619a619bc40e4abdbbf2a1b5a971'
});
oxr.latest(function(error) {
if ( error ) {
// `error` will contain debug info if something went wrong:
console.log( 'ERROR loading data from Open Exchange Rates API! Error was:' )
// Fall back to hard-coded rates if there was an error (see readme)
reject(error.toString());
}else{
// To load rates into the money.js (fx) library for easier currency
// conversion, simply apply the rates and base currency like so:
fx.rates = oxr.rates;
fx.base = oxr.base;
// money.js is now initialised with the exchange rates, so this will work:
var amount = fx(data.price).from(data.currency).to('INR').toFixed(6);
//var obj = {expDetails: exp,convertedCurrency : amount};
data.amount = amount;
results.push(data);
console.log(results)
}
});
});
resolve(results)
console.log(results) printing correct data. but in resolve(results) there is not any push amount data showing?
Upvotes: 0
Views: 105
Reputation: 5088
You are calling oxr
api eachtime while looping, You can call oxr
api once and after getting the rates
and price
you can update results data by calculating amount as follows:
const fx = require('../lib/money');
const oxr = require('open-exchange-rates');
oxr.set({
app_id: 'd5e619a619bc40e4abdbbf2a1b5a971'
});
oxr.latest((error) => {
if (error) {
console.log('ERROR loading data from Open Exchange Rates API! Error was:')
reject(error.toString());
} else {
fx.rates = oxr.rates;
fx.base = oxr.base;
let finalResult = results.reduce((finalResult, data) => {
let amount = fx(data.price).from(data.currency).to('INR').toFixed(6);
data['amount'] = amount;
return [...finalResult, data];
},[]);
resolve(finalResult);
}
});
Upvotes: 1