0

Why isn't thenResolve working as I expect?

I have a method in a javascript module:

function addVisit(companyId) {
    var  newVisit;

    return getInventoryItems()
        .then(function(data) {
            newVisit = createVisit(companyId, data);
        })
        .then(function() {
            breezeVisitsManager.saveChanges();
        })
        .thenResolve(newVisit);
}

That is called by another module:

visitRepository.addVisit(self.companyId)
    .then(function(newVisit) {
        var route = self.visitRoute(newVisit.VisitId());
        router.navigate(route);
     }

newVisit exists at the time thenResolve is called, but it's undefined when the calling code receives it. I've played around with the sample JSFiddle and I don't understand why my code isn't working.

Jamie Ide
  • 48,427
  • 16
  • 81
  • 117

1 Answers1

4

newVisit is undefined at the time you pass it to .thenResolve (immediately when addVisit is called).

function addVisit(companyId) {
    var  newVisit;

    return getInventoryItems()
        .then(function(data) {
            newVisit = createVisit(companyId, data);
        })
        .then(function() {
            breezeVisitsManager.saveChanges();
        })
        .then(function(){
            return newVisit;
        });
}

Promises don't change the language, a.b.c() will still call c() immediately no matter what.

Esailija
  • 138,174
  • 23
  • 272
  • 326
  • Thanks for the answer, I'll try this later. However, the Q API documentation says about thenResolve "A sugar method, equivalent to promise.then(function () { return value; })", so isn't your answer identical to my code? And I don't get your last sentence -- assuming a, b & c are promises, a function supplied to c will not be called until a, b & c are fulfilled. – Jamie Ide Nov 06 '13 at 19:11
  • 1
    @JamieIde No - it seems you are new to Javascript. They are not literally equivalent, like in this case they are not because `newVisit` is not a value but a variable. I guess the documentation could be improved on that part. The language doesn't know if something is a promise everything in `a().b().c()` is executed immediately. However, any functions passed to a, b or c are called by code which makes promises work however they do. – Esailija Nov 06 '13 at 19:45
  • On the contrary, I've been working with Javascript for more than 10 years but I'm new to promises. I tried your answer and it works, so thanks for that. – Jamie Ide Nov 06 '13 at 20:08