I am working with an API which expects me to pass the first four digits of a card and it returns me the card country. Now, here is my problem. It turns out that the function that I am calling is asynchronous and when I try to return the country, it actually goes to the return value before even the async call is fully executed. I wanted the call to be synchronous which means I dont want the function to return me the default data and wait for the actual response from the API. This is what I tried so far. I actually used console.log() statement to figure out the whole problem.
module.exports = {
bvncheck: function (cardnum) {
console.log("cardnumber", cardnum);
flutterwave.BIN.check(cardnum, function (req, res) {
var country = res.body.data.country;
console.log("country", country);
return country;
});
}
};
app.post('/checkcardbin', function (req, res) {
var cardnumber = req.body.cardnumber;
//var r = fd.bvncheck(cardnumber);
var r = fd.bvncheck(cardnumber);
console.log("result", r);
});
I expected the following output in the following order-
1. cardnumber *****
2. country *****
3. result ******
But in reality, it is returning me in the following order and due to the asynchronous nature, I am getting result to be undefined because the data is returned before the function is actually done executing.
1. cardnumber *****
2. result ******
3. country *****
How can I solve this issue? Any suggestions or advise is highly appreciated.