Ting Lee
Ting Lee

Reputation: 33

the argument of the promise object's method then()'s callback function

I am new to angular, I did some research but still cannot find an answer..., I have the following code:

promiseB = promiseA.then(function(result) {
  return result + 1;
});

Why we can use result as the argument of the callback function? How the returned stuff of promiseA becomes result ?

Thanks everyone!

Upvotes: 0

Views: 48

Answers (3)

Check how using the $q service you can defer the promise returned and process in sucesives callbacks, the defer.promiseit's the key.

var promiseB = myService.response().then(function(result){
            var defer = $q.defer();
            defer.resolve(result);
            return defer.promise;
        });
promiseB.then(function(result){
            console.log("In promise B ===>", result);
        });

check this codepen: http://codepen.io/gpincheiraa/pen/ONjMrR?editors=0010

Upvotes: 0

Richard Pressler
Richard Pressler

Reputation: 494

When promiseA completes ("resolves"), it will call the function that you pass to the then() function, and pass the result into that function. So let's say I had a promise that is requesting information from a database query. Let's say it's going to (eventually) give me the phone number for a user. I'd set up my code to print that out like this:

myPromise.then(function(phoneNum) {
    console.log(phoneNum);
});

The reason we can't just say var result = myPromise() is because a promise executes in a different flow that the rest of the code. We need to set up a function to handle the result when it's done

Upvotes: 1

Duncan
Duncan

Reputation: 95652

A promise is simply an object used to represent the pending activity, don't confuse it with the result of that activity.

The resolved value is passed to the success callback that was given to the .then() method. If promises are chained together then the value returned from that callback becomes the value passed to the next .then() (or if the value returned is also a promise the resolution of that promise is passed to the next .then()).

So in your particular example we don't know where result came from: whatever created promiseA simply ensured it resolved with that value. However we do know that promiseB will resolve with the value result+1 because that's what you returned.

Upvotes: 1

Related Questions