0

I am trying to do promise chaining, but I am getting undefined for a part in my chain and I am unsure why. The issue seems to be when I am using serviceFactory.GetProjectManager(). When I return that it doesn't seem to be returning a promise, but instead automatically goes into the next .then() with a resolved value of undefined.

If GetProjectManager returns a string and I return that from the function call won't it wrap it in a promise and be passed to the next promise chain?

  dataFactory.GetProject()
    .then(function(result){
        return result.Response.ProjectId;
    }).then(function(projectId){
        return serviceFactory.GetProjectManager(projectId);
    })
    .then(function(result){
        //GET UNDEFINED HERE <---------
    })
    .catch(function(error){

    });

If I write the code like below, then it will return the right value in the callback, but I do not want to use callbacks I want to use flattened promise chaining.

dataFactory.GetProject()
    .then(function(result){
        return result.Response.ProjectId;
    }).then(function(projectId){
        serviceFactory.GetProjectManager(projectId
            ,function(result){
                //Returns Project Manager Here <----
            }
            ,function(error){

        });
    })
    .catch(function(error){

    });
gyre
  • 16,369
  • 3
  • 37
  • 47
FillyPajo
  • 113
  • 1
  • 2
  • 8

1 Answers1

1

As you pointed out in the comments, GetProjectManager seems to accept a callback (and return undefined) rather than returning a Promise.

You can wrap your original callback-based function into a function that returns a promise, and call that instead:

function GetProjectManagerAsync (serviceFactory, projectId) {
    return $q(function (resolve, reject) {
        serviceFactory.GetProjectManager(projectId, resolve, reject)
    })
}

dataFactory.GetProject()
    .then(function(result){
        return result.Response.ProjectId
    })
    .then(function (projectId){
        return GetProjectManagerAsync(serviceFactory, projectId)
    })
    .then(function (projectManager) {
        // do something neat with `projectManager`
    })
    .catch(function (error){
        throw error // or do real error handling
    })

There are also great libraries that will do this for you automatically, like Thenify.

Edit: Thanks Bergi for pointed out that Angular.js promises would make more sense here.

gyre
  • 16,369
  • 3
  • 37
  • 47