Reputation: 532
I m new in asynchronous coding
I m using csvtojson library and I'm trying to convert a csv file and pass the result in an other module .
The convert() function looks like this:
convert: function (csvFilePath) {
return new Promise((resolve, reject) => {
const options = { delimiter: ["|",","],
noHeader: true ,
headers: ["header1", "header2"]
}
csv(options)
.fromFile(csvFilePath)
.on('end_parsed',(convertedJson) => {
resolve(convertedJson);
})
.on("done",(error) => {
reject(error);
})
});
}
My call:
const converter = require ("./converter")();
let json;
json = converter.convert("./importSample.csv");
console.log(json);
When I execute the code I can see that the promise is still on pending state:
Promise { <pending> }
I think that I have to use the .then()
function but I don't know where or how.
Upvotes: 1
Views: 523
Reputation: 5708
From converter
function you are getting promise, and that object has method then
. You should do something like this.
const converter = require ("./converter")();
converter.convert("./importSample.csv").then(json => {
console.log(json);
}).catch(error => {
console.log(error);
});
Here you can find nice tutorial about Promises, and here is documentation for Promises.
Upvotes: 4
Reputation: 724
Promise has a fixed syntactical architecture. I'll explain it with a simple code.
var x = new Promise((resolve,reject)=>{
//here you perform an asynchronous call
resolve(value); //receive it in 'then' part of promise
reject(error): //if your operation fails due to any error, you call reject, which is handled by 'catch' part of the promise.
});
x.then((value)=>{
//this is the part which was called using resolve, and the value it receives is the value you passed as argument in resolve.
});
x.catch((error)=>{
//this part is called by reject. the error received is the value you passed inside the reject.
});
So, your function should go something like-
converter.convert("./importSample.csv").then((json)=>{
//here is your part of code which is to be handled synchronously after the promise is called.
}).catch((error)=>{
//in case any error occurs and you want your program to exit gracefully.
});
Upvotes: 1