Reputation: 332
I am trying to apply a custom function inside a Post Request, but it returns undefined.
I know that this is some kind of async issue, I just cant figure out what might be the problem.
Chunk of code where problem resides
console.log(text); // <---- This shows correct value
A.prepare(function (text) {
console.log(text) // <---- This shows undefined
B.write(text, function (response) {
sendTextMessage(sender,response.message)
return response.message;
});
});
Whole code
app.post('/webhook/', function (req, res) {
// addPersistentMenu();
let messaging_events = req.body.entry[0].messaging;
for (let i = 0; i < messaging_events.length; i++) {
let event = req.body.entry[0].messaging[i];
let sender = event.sender.id;
if (event.message && event.message.text) {
let text = event.message.text;
console.log(text);
A.prepare(function (text) {
B.write(text, function (response) {
sendTextMessage(sender,response.message)
return response.message;
});
});
}
if (event.postback) {
let text = JSON.stringify(event.postback);
sendTextMessage(sender, "Postback received: "+text.substring(0, 200));
continue;
}
}
res.sendStatus(200)
});
Upvotes: 0
Views: 103
Reputation: 6232
You are getting
text
value asundefined
since you are accessing it in acallback function
. And you have also giventext
parameter in thecallback function
. AndPriority always goes to local
that means every time you'll get the local value oftext
which isundefined
now. you must change one of those variable names.
As I have changed text
to text1
now you can get text1
value in callback function
And if you want to pass variable in
A.prepare()
function, you can add multiple parameters on basis of requirement.
like this:
A.prepare(param1,param2,param3,...,function(text){
//Do your stuff
})
Here is you updated code:
app.post('/webhook/', function(req, res) {
// addPersistentMenu();
let messaging_events = req.body.entry[0].messaging;
for (let i = 0; i < messaging_events.length; i++) {
let event = req.body.entry[0].messaging[i];
let sender = event.sender.id;
if (event.message && event.message.text) {
let text1 = event.message.text;
console.log(text1);
A.prepare(function(text) {
B.write(text1, function(response) {
sendTextMessage(sender, response.message)
return response.message;
});
});
}
if (event.postback) {
let text = JSON.stringify(event.postback);
sendTextMessage(sender, "Postback received: " + text.substring(0, 200));
continue;
}
}
res.sendStatus(200)
});
Upvotes: 1
Reputation: 6280
It's a scope issue, not an async one.
In the line
A.prepare(function (text) {
text
is actually the parameter passed to the function and used internally to the function itself. It does not refer to text you are logging in the line above.
Upvotes: 1