I am not sure whether the success callback of Twilio Authy's register_user()
is firing or not. In my code
var authyUsrId;
//global.authyUsrId;
app.post('/forTwilio', function(req, res){
// send the received data to Twilio Authy
authy.register_user('maverick@example.com', '8753565612', '91', function(err, res){
//global.authyUsrId = 'world';
authyUsrId = 'world';
});
//res.set("Content-Type","application/json");
res.json({name: 'hello', msg: authyUsrId});
//res.json({name: 'hello', msg: global.authyUsrId});
});
Although new user is being added successfully to Authy and the response status is 200.
I want to set the value of authyUsrId to something in the success callback of register_user()
and use it in the JSON response that I am sending to the POST request.
But in the response I am getting only this
{name: 'hello'}
Is there any way to debug particularly the register_user() callback portion?
Twilio developer evangelist here.
I see you've solved the issue in your answer, however I just wanted to explain what was going on and why that was the solution for you.
In your original code:
app.post('/forTwilio', function(req, res){
authy.register_user('maverick@example.com', '8753565612', '91', function(err, res){
authyUsrId = 'world';
});
res.json({name: 'hello', msg: authyUsrId});
});
You set the authyUsrId
variable within your callback from the API request to Authy. You then try to use that authyUsrId
in the call to respond with JSON. However, register_user
is an asynchronous call, so the code below it runs before the code that is run within the callback. In fact, the reguster_user
function has to make an HTTP request, so the callback is only run once that request is completed.
If you added logging to your original code, like this:
app.post('/forTwilio', function(req, res){
authy.register_user('maverick@example.com', '8753565612', '91', function(err, res){
console.log("Received response from Authy");
authyUsrId = 'world';
});
console.log("Sending JSON response");
res.json({name: 'hello', msg: authyUsrId});
});
You would see in your log:
Sending JSON response
Received response from Authy
Your fix was to respond to you original web request within the callback, when you have all the data you needed. And that's why it works. If I were updating your original code it would now look like:
app.post('/forTwilio', function(req, res){
authy.register_user('maverick@example.com', '8753565612', '91', function(err, res){
authyUsrId = 'world';
res.json({name: 'hello', msg: authyUsrId});
});
});
Hope this makes sense.