Use promise in Angular Js 1

// Story: One morning, a father says to his son: "Go and get the weather forecast, son!"
// Every Sunday morning, a father asks his son to go and find out the weather forecast for the afternoon, by using his super-strong telescope to look across the horizon from the tallest hill by their house. The son promises his dad he will go and get the weather forecast. He creates a promise with his dad at the door when he leaves.
// At that point, the dad decides if the weather tomorrow is good, he'll prepare a fishing trip for tomorrow. If it's bad he won't. Also, if the son is unable to get a forecast, he'll stay in as well.
// After 30mins or so, the son comes back. Different things happen from week-to-week
// ---------------------------------------------------------------------------
// can detect the result
var prepareFishingTrip = function (data) {
    console.log('the weather is fine');
var prepareSundayRoastDinner = function prepareSundayRoastDinner (data) {
    console.log('the weather is bad');
// can't detect the result
var dontKnowPrepareSundayRoastDinnerOrNot = function prepareSundayRoastDinner (res) {
    console.log('the son can\'t retrieve the weather, he return everything');
angular.module('myApp', [])
.factory('SonService', function ($http, $q) {
    return {
        getWeather: function() {
            // the $http API is based on the deferred/promise APIs exposed by the $q service
            // so it returns a promise for us by default
            return $http.get('')
                .success(function(res) {
                    if (typeof === 'object') {
                    } else {
                        // invalid response
                        return $q.reject(res);
                .error(function(res) {
                    // something went wrong
                    return $q.reject(res);
.controller('Ctrl', function($q, SonService) {
        // success() called when son gets back
        .success(function(data) {
            // promise fulfilled
            if (data.wind && data.wind.speed > 2) { // if success
            } else {
                prepareSundayRoastDinner(data); // if the weather is not good
        .error(function(res) {
            // promise rejected

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s