I am trying to get some data from csv file, then make some magic with them and create an object with this derived data. I created this function by using module.exports I exported it.
var csvtojson = require('csvtojson');
var data = [];
module.exports = function createStock(name){
var myObj = {};
csvtojson().fromFile('./csv-raw/'+name+'.csv')
.then(source => {
source.forEach(value => {
var row = {};
row.Date = value.Date;
row.Dividend_Yield = value.Dividend_Yield;
row.Gross_Dividend_Per_Share = value.Gross_Dividend_Per_Share;
row.Distribution_Rate = value.Distribution_Rate;
data.push(row);
});
})
.then(() => {
myObj = {
name: name,
data: data,
summary: {a: Math.random(), b: Math.random(), c: Math.random()}
};
})
.then(() => {
console.log(myObj)
return myObj
})
}
And import to the route;
const createdStock = require('../../modified');
router.get('/new/:stockName', async (req,res) => {
var stock = await createdStock(req.params.stockName);
setTimeout(() => {
console.log(stock);
}, 2000);
(I can see the result of console.log(myObj) inside first file)
(I can not see console.log(stock); inside second file)
I tried to figure out the problem whether stems from async behavior of JS but could find any solution ?
Generally my question is how can I send data that is created inside of .then block to another JS file.
In your createStock
function you need to return your call to csvtojson
. That will return the Promise making the await
work properly. Then you won't need the setTimeout
and you can just console.log(stock)
.
module.exports = function createStock(name){
var myObj = {};
return csvtojson().fromFile('./csv-raw/'+name+'.csv')
...
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.