I am making a payment gateway for my web site and I have problem with my debugger. Even I have used async await even then some particular lines are executed asynchronously but when another function comes it runs sync. For better understanding have a look on the actual code mentioned below
This is my app.js file
app.post('/pay', async function(req,res){
let response = await orderApi.pay(req.body) // First debugger goes here (1)
res.json(response) // (need this line to be executed when pay function is completed) (4)
console.log(response)
And this is my order API file
exports.pay = async function (body) {
var headers = { //then here debugger comes (2)
'X-Api-Key': 'test_d5f178f6f910a5ec48a429d540d',
'X-Auth-Token': 'test_f3f32cda3a7aafc2a188579530f'
}
var payload = {
purpose: body.purpose,
amount: body.amount,
phone: body.phone,
buyer_name: body.buyer_name,
}
request.post('https://test.instamojo.com/api/1.1/payment-requests/', { form: payload, headers: headers }, function (error, response) { // (3) !!!
var parsed = JSON.parse(response.body); // then it does not goes here then it goes back in app.js file (5)
var redirectu = parsed.payment_request.longurl (6)
return redirectu
})
}
I am not able to understand what problem it please help me to figure it out // remember the points like (1),(2).. they are the numbers where my debugger goes
You probably want to return what's coming back from
request.postwhich means that we should modify the code to something like the following:Explanation
The
returninside the callback ofrequest.postis returning after the function already finished executing and since there's no explicit return in the outer function, it just callsrequest.postand (implicitly) returnsundefinedwithout waiting for therequest.postto finish executing.