Reputation: 423
I'm using fast csv for csv file read below is code given below
var csv = require("fast-csv");
csv.fromPath("userlists.csv")
.transform(function(obj){
return {
email: obj.email,
firstname: obj.firstname,
lastname: obj.lastname
};
})
.on("data", function(data){
// Some promise call for API
})
.on("end", function(){
response.send("Imported successfully");
console.log("done");
});
Inside on("data", function(data){}) I'm calling some API using promise these API takes some time for processing. After reading csv file "Imported successfully" is showing immediately without waiting for API processed. I want to print Imported successfully at end of all API processing.
Upvotes: 1
Views: 2820
Reputation: 3141
on("data", function(data){})
don't have full data. It call for every record. If we put api inside this, then this may call many time API.
on("end", function() {})
execute after csv import success. It's not depend on any api, It's dependency only csv import.
We have two approach to do this.
end
methodstore data in array and finally call in on("end", function() {})
method.
var csvdata = [];
var csv = require("fast-csv");
csv.fromPath("userlists.csv")
.transform(function(obj){
return obj;
})
.on("data", function(data){
csvdata.push(data);
})
.on("end", function(){
// Some promise call for API
// In API promise callback
response.send("Imported successfully");
console.log("done");
});
If first approach not suitable for condition then we can use this approach. but first approach is more better.
In this approach we create a callback function which we call in api callback. As we know api call multiple time in this approach, because this on("data"
method call for every record. so we need to call after all api success.
var csv = require("fast-csv");
csv.fromPath("userlists.csv")
.transform(function(obj){
return {
email: obj.email,
firstname: obj.firstname,
lastname: obj.lastname
};
})
.on("data", function(data){
// Some promise call for API
// promises callback handle
Promise.all([/*api promise list here*/]).then(function() {
handleSuccessResponse(response);
}
})
.on("end", function(){
});
function handleSuccessResponse(response) {
response.send("Imported successfully");
console.log("done");
}
Upvotes: 1