Reputation: 1362
I am quite new in promises and I think I don't understand it correctly because I am trying it in my code without success.
I have a server on NodeJS, using Express library and express-promise
var express = require('express');
var app = express();
app.use(require('express-promise')());
Then I am handling ajax query:
var promise = function() {
for(var query in req.query ){
console.log( 'query: ', query );
switch( query ){
case 'getobserved':
results.observedTags = getObserved();
break;
...
}
}
};
And getObserved is getting data from Firebase DB
var getObserved = function() {
var observedTags = dbRef.child('observedTags');
observedTags.on('value', function(snap) {
var allObservedItems = snap.val();
var list = [];
for(var ii in allObservedItems ){
list.push( allObservedItems[ii].name );
}
return list;
});
};
And finally I am trying to send response to client by:
promise.then( res.send( results ), someRejectedMethod );
And I get in console this:
TypeError: undefined is not a function
at d:\wamp\www\soz2\server.js:100:13
Probably method "promise" is undefined. I am not sure if I use express-promise wrong, or it's just my lack of knowledge about whole promises. Need some hint, please
Upvotes: 0
Views: 973
Reputation: 664206
Probably method "promise" is undefined.
No, the promise
function seems to be defined. Only it is a function, not a promise object, and has no .then
method.
I am not sure if I use express-promise wrong
Yes. From how I understand their docs, all it seems to do is make res.send
, res.json
, and res.render
accept promises or objects that contain promises, which are then recursively expanded and awaited.
or it's just my lack of knowledge about whole promises.
That as well. I recommend the general promise resources as an entry point to learn about promises.
First, you will have to promisify your Firebase methods so that getObserved
does return a promise. (Currently, it seems to fail because you try to return
from an async callback). You'll probably have to choose a promise libary if you aren't already using one.
Then, in your route you can use it like
for (var query in req.query) {
console.log('query: ', query);
switch(query) {
case 'getobserved':
results.observedTags = getObserved(); // a promise
break;
…
}
}
res.json( result ); // here, express-promise does some magic
No need for the var promise = function() {
line. And you probably can scrap promise.then( res.send( results ), someRejectedMethod );
as well, as express-promise does handle this for you. If you didn't use it, you could have done it explicitly with something like
var promise = getObserved();
promise.then(function(list) {
res.json({observedTags: list});
}, someRejectedMethod);
Upvotes: 1