Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm new to Promises and I don't know the best practises. The following code retrieves page history then search history. I want this history to be saved in variables in order to use it later. I wrote this code but I don't know if it's the best approach. Can you please give me your opinion?

/** Let's analyse page&search history */
var history = {};

var savePage = function(obj) 
{
    var defer = Q.defer();
    history.page = obj;
    defer.resolve();
    return defer.promise;
}

var saveSearch = function(obj) 
{
    var defer = Q.defer();
    history.search = obj;
    defer.resolve();
    return defer.promise;
}

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

/** Promises chain */
historyLib.get_entries_of(uid, "page")
.then(savePage, console.log)
.then(historyLib.get_entries_of(uid, "search"))
.then(saveSearch, console.log)
.then(displayHistory);
share|improve this question

closed as off-topic by Flambino, Alex L, syb0rg, Simon André Forsberg, rolfl Jun 14 at 23:36

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions containing broken code or asking for advice about code not yet written are off-topic, as the code is not ready for review. Such questions may be suitable for Stack Overflow or Programmers. After the question has been edited to contain working code, we will consider reopening it." – Flambino, Alex L, syb0rg, Simon André Forsberg, rolfl
If this question can be reworded to fit the rules in the help center, please edit the question.

    
Does it work? I have my doubts about the 2nd call to get_entries_of; it's being called immediately, and returning a promise (as far as I can tell), neither of which is what I think you're going for. –  Flambino Jun 14 at 15:48
    
You're right! I didn't noticed history.search was undefined. So how can I 1) Call get_entries_of(uid, "page") 2) Save the result 3) Call get_entries_of(uid, "search") 4) Save the result ? –  Hey Jun 14 at 18:55
1  
Welcome to Code Review! You might have misunderstood what this site is about. We help with improving the cleanliness of existing, working code. We are not the site to ask for help in fixing or changing what your code does. Once the code does what you want, we would love to help you do the same thing in a cleaner way! –  Simon André Forsberg Jun 14 at 20:23
add comment

Browse other questions tagged or ask your own question.