Node.js callback called twice - node.js

I'm using the sendgrid library for node.js. Currently there is a callback that it's getting fired twice.
#invite = (email, agencyId, callback) ->
(app.get 'agencies').findOne {_id: agencyId}, {name:1}, (error, agency) ->
sendgrid.send {
to: email,
from: 'yamil.asusta#upr.edu',
subject: "You have been invited to #{agency.name}",
html: "<html><body>Have fun</a></body></html>"
}, (success, message) ->
console.log arguments
if success
console.log callback
callback()
else
console.log message
This is what I get from the console
{ '0': true, '1': undefined }
[Function]
{ '0': false, '1': 'Invalid JSON response from server' }
Invalid JSON response from server
The thing is, I invoke the function from 1 route and it works perfectly fine. If I invoke it from another separate route, it fires the callback but, it says the callback variable (function) is undefined.
Any clues?

I suggest you log the arguments to the #invite function. I suspect that is getting called twice, once with correct arguments and once with incorrect arguments due to a bug elsewhere in your program.

Related

Error in invocation of runtime.sendMessage (Chrome API)

The goal is to send a message to a content script from a background script after a URL is changed.
Here is my function:
chrome.tabs.onUpdated.addListener(
function (tabId, changeInfo, tab){
if(changeInfo.url && changeInfo.url.includes('https://example')){
chrome.runtime.sendMessage(tabId, {warn: 'message'}, function(resp){})
}
});
But I get an error: Error, in event handler: TypeError: Error in invocation of runtime.sendMessage(optional string extensionId, any message, optional object options, optional function callback): Error at parameter 'options': Unexpected property: 'warn'.
I tried to code according to documentation, but can't find the error
I was getting a similar error until I did something like
chrome.tabs.sendMessage(tabId, {warn: 'message'});
Note: tabs, not runtime method.
I had to leave out the message parameter. Not sure about callback.
You are using the API wrong. sendMessage should receive two parameters. The first one can be an object and the second one would be a callback with the response. This way:
chrome.runtime.sendMessage(
{
message: "this is a message",
},
(response) => {
// ... do something with the response
}
);

How to return a value from a function that uses 'http.get()' method in Node.js?

I have a simple HTTP GET function that only needs to return the response in a function, but right now this function is returning void.
The code in sitechecks.js
var checkSite = () => {
https.get('https://itmagazin.info', (res, err) => {
if (res.statusCode === 200 && res.statusMessage === 'OK') {
return `The site returned: ${res.statusMessage}`
} else return `Error, the site returned: ${err.message}`
})
}
module.exports = checkSite
And when I import the module in index.js, the console returns [Function: checkSite] and not the value itself.
// Index.js
var extSiteCheck = require('./sitechecks')
// This console prints [Function: checkSite] instead of "OK"
console.log(extSiteCheck.checkSite)
However, if I add the return statement on http.get() in the function, the console prints undefined. So I thought that this undefined is a progress, but I don't understand why does it return undefined?
(return http.get() in the checkSite function)
Any help, tips is appreciated.
Because callbacks in JavaScript are asynchronous, you can't return from within a callback.
That means this
console.log(extSiteCheck.checkSite)
runs before the request comes back.
You can try console logging within your callback (instead of trying to return a value), in order to see this in practice. But basically, whatever you are trying to achieve with the results of your get request, you need to do inside the callback.
mebbe something like ... console.log( extSiteCheck.checkSite() );

How and when to return values properly with promises in google cloud functions?

I'm slowly working my way through Node.js. I've got a basic iOS app (swift) that pushes a message to Firestore and I'm using Node to send a notification when the database is updated.
exports.updateRequestToJoin = functions.firestore
.document('/chats/{chatId}')
.onUpdate(event => {
if(userId != sentBy)
{
return db.collection('users').doc(userId).get().then(doc => {
var payload = {
notification:{
title: "msg",
body: "send msg"
}
};
admin.messaging().sendToDevice(fcm_token, payload)
.then(function(response) {
// See the MessagingDevicesResponse reference documentation for
// the contents of response.
console.log("Successfully sent message:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
};
return 0
});
Initially, I just had return at the end of the function but was getting the error "Function returned undefined, expected Promise or value" until I used return 0 and that seemed to silence the error.
The things I was unsure about are:
Is returning a value like 0 ok practice?
When the error says "expected Promise or value" does the promise refer to the .then?
In the if statement, I return the db.collection - is that necessary to return that or can I skip the return keyword?
Thanks.
You have good questions here. The place to start is with the function caller. You are exporting updateRequestToJoin(). What is the caller expecting? Are you thinking in terms of exiting the function with a success or failure code? Node apps tend to work differently than scripting environments that return only boolean values. The whole node ethos is about supporting a single thread environment that is happy to execute asynchronously. So, node functions tend either to return Promises, with their built-in resolve or reject methods; or they run a callback.
If you want to merely return a success code in your then statement, or a failure code in your catch statement, you could something as simple as this:
if(userId != sentBy)
{
db.collection('users').doc(userId).get().then(doc => {
var payload = {
notification:{
title: "msg",
body: "send msg"
}
};
admin.messaging().sendToDevice(fcm_token, payload)
.then(function(response) {
// See the MessagingDevicesResponse reference documentation for
// the contents of response.
console.log("Successfully sent message:", response);
return true;
})
.catch(function(error) {
console.log("Error sending message:", error);
return false;
});
};
The success or failure is returned in the then/catch of your admin.messaging chain.
That's sort of the answer to your first question and a partial answer to your second. A more complete answer to your second question requires a bit of reading. Promise is a native Javascript object that gives you convenience methods to handle asynchronous execution. The db.collection chain you are calling, and the admin.messaging chain are Promises (or some sort of thenable construct) that are returning a resolve in the then, and a reject in the catch (you are not using the catch side of the db.collection call, but you are using the catch side of the admin.messaging call).
Finally, as to whether you need to return the db.collection chain, you would do this if the db.collection call was a part of a Promise.all execution of an array of function calls. In this case, however, it looks like you want to simply return a success or failure code, based on the success or failure of your admin.messaging call.
I am making some assumptions about your goal here. Hopefully, at least, this moves the discussion toward clarity.

MongoDb and Nodejs Server Response

In my javascript class, i have a function that return a list of things like so,
//ProjectClass.js
getProjectList: () =>
#Project.find (err, projects) =>
console.log(projects)
return projects
However, whenever I try to send a server response from nodejs
//App.js
project = new projectSchema.Project()
res.send(project.getProjectList())
I get the following as a response
{
"options": {
"populate": {}
},
"_conditions": {},
"_updateArg": {},
"op": "find"
}
Ironically, if I pass the res object to my getProjectList and send server response from my getProjectList function then everything works just fine.
Thanks for the help!
#Project.find is an asynchronous function, calling your anonymous callback once the find results are available. getProjectList returns the result of the last synchronous statement executed in that function which is the return value of #Project.find. That's not the projects array your callback returns but the query object you see in your response.

nodejs express- server's get method gets 3 arguments

Can you please help me understand the following code? It seems that here the get method receives 3 arguments instead of 2.. What does it do with the object that is given to it as the third argument?
app.get('/query', function(req, res) {
console.error('we shouldn't be here');
res.writeHead(500);
res.end('we shouldn't be here' + req.url);
},
{
id: 'my_id',
name: 'query',
usage: 'get query',
example: 'get query',
params: {},
broadcast: true,
response: { representations : [ 'application/json' ] }
}
);
Thanks,
Li
This doesn't appear to be correctly written. In Express, a request handler can take a third paramater which is a function (commonly called next() which will be called if the handler decides not to handle the request (thus passing the request down to the next handler you defined). In your example, however, the third parameter is on object rather than a function, and it's not actually being passed to your request handler..
It's possible that you're basing your code on an example that uses a very early, now obsolete, version of Express.

Resources