Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

better document promise chaining with then #11708

Closed
@jnizet

Description

@jnizet

The documentation of $q says about the function then():

This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback.

This is not completely true, and I think the missing part is one of the reasons of many bad usages of the promise API. Consider this example, which tries to get the weather on departure time or a flight:

function getWeather(flight) {
    return $http.get('http://flights.com/departures/' + flight).then(function(departure)
        return $http.get('http://weather.com/' + departure.data.time');
    );
}

The documentation says that then() returns a new promise which is resolved via the return value of the successCallback. So I'd expect from the documentation that the returned value is a promise resolved with a promise of weather. I would thus have to do

getWeather(1234).then(function(weatherPromise) {
    weatherPromise.then(function(response) {
        $scope.weather = response.data;
    }));

But that's incorrect, because it's not how it actually works. The behavior is not documented, but if the success callback returns a promise A, the then() function returns a promise that is not resolved with A, but with the result of A. The correct usage is thus

getWeather(1234).then(function(response) {
    $scope.weather = response.data;
});

This chaining usage should be documented.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions