简体   繁体   中英

Node.js Promises: get & save results

I'm new to Node.js promises, I want to do something pretty basic: retrieve "searches" entries in the history db, retrieve "pages" entries in the history, then display the both.

I've written this piece of code but it doesn't work. The second get_entries_of doesn't work because the final console.log is called before it has enough time to call the db. Can you help me?

var history = {};

var savePage = function(obj) 
{
    history.page = obj;
}

var saveSearch = function(obj) 
{
    history.search = obj;
}

var displayHistory = function()
{
    console.log(history);
}

/** Promises chain */
historyLib.get_entries_of(uid, "page")
.then(function(obj) {
    savePage(obj);
    historyLib.get_entries_of(uid, "search");
}, console.log)
.then(function(obj) {
    saveSearch(obj);
    displayHistory();
}, console.log);

get_entries_of:

function get_entries_of(uid, type, date_start, date_end)
{
     var deferred = Q.defer();

var extra = "";
if(typeof(date_start) !== 'undefined')
    extra = ' ,"date": {"$gte": ' +date_start+ ', "$lt": ' +date_end+ '}';

history[type].find({ _uid: mongoose.Types.ObjectId(uid) + extra}, deferred.makeNodeResolver());

return deferred.promise;
}

Without more details, it looks like your first promise callback doesn't return a promise. So that first search probably needs to look like this:

historyLib.get_entries_of(uid, "page")
.then(function(obj) {
    savePage(obj);
    return historyLib.get_entries_of(uid, "search");
}, console.log)
.then(/* go on here with the second search */)`

So once again: return historyLib.get_entries_of(uid, "search");

Note we return a promise here? Actually we return whatever get_entries_of returns which is a promise. It means that this whole callback (function(obj){}) will also return a promise and whatever that function returns will be appended on the promise chain.

That's why your second promise will also work. Otherwise it would look like your first then(cb) callback (the cb thing) returns undefined, and you cannot call then() of undefined.

What does your console.log say, anyway?

Also on a side note, are you sure that this query works when you pass it the start_date too? This: { _uid: mongoose.Types.ObjectId(uid) + extra} doesn't look correct, but I might be wrong. To me it looks like you want:

var criteria = {_uid: uid};
if(date_start) {
    criteria.date = {
        $gte: date_start
    };// etc
}
stuff.find(criteria, callback); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM