EzDevInfo.com

promise interview questions

Top promise frequently asked interview questions

How is a promise/defer library implemented? [closed]

How is a promise/defer library like q implemented? I was trying to read the source code but found it pretty hard to understand, so I thought it'd be great if someone could explain to me, from a high level, what are the techniques used to implement promises in single-thread JS environments like Node and browsers.


Source: (StackOverflow)

Using success/error/finally/catch with Promises in AngularJS

I'm using $http in AngularJs, and I'm not sure on how to use the returned promise and to handle errors. I have this code:

$http.get(url)
.success(function (data) {
    // Handle data
})
.error(function (data, status) {
    // Handle HTTP error
})
.finally(function () {
    // Execute logic independent of success/error
})
.catch(function (error) {
    // Catch and handle exceptions from success/error/finally functions
});

Is this a good way to do it, or is there an easier way?


Source: (StackOverflow)

Advertisements

AngularJS resource promise

I've got a simple controller that use $resource :

 var Regions = $resource('mocks/regions.json');

 $scope.regions = Regions.query();

I'm using this controller in a directive (in the link function)

var regions = scope.regions;

But regions is undefined. It's pretty logic the call is asynchronous.

My question is how can i do to wait the result and regions be an array with all data ?

UPDATE : 

Here the definition of the directive

app.directive('ngMap', function () {
            return {
                restrict: 'EA',
                replace: 'true',
                scope: {

                },
                template: '<div id="map"></div>',
                controller: 'AccordMapCtrl',
                link: function (scope, element, attrs) {
                    var regions = scope.regions;
                    console.log(regions);

                    for (var region in regions) {
                    }
            };
        });

Source: (StackOverflow)

Wait for all promises to resolve

So I have a situation where I have multiple promise chains of an unknown length. I want some action to run when all the CHAINS have been processed. Is that even possible? Here is an example:

app.controller('MainCtrl', function($scope, $q, $timeout) {
    var one = $q.defer();
    var two = $q.defer();
    var three = $q.defer();

    var all = $q.all([one.promise, two.promise, three.promise]);
    all.then(allSuccess);

    function success(data) {
        console.log(data);
        return data + "Chained";
    }

    function allSuccess(){
        console.log("ALL PROMISES RESOLVED")
    }

    one.promise.then(success).then(success);
    two.promise.then(success);
    three.promise.then(success).then(success).then(success);

    $timeout(function () {
        one.resolve("one done");
    }, Math.random() * 1000);

    $timeout(function () {
        two.resolve("two done");
    }, Math.random() * 1000);

    $timeout(function () {
        three.resolve("three done");
    }, Math.random() * 1000);
});

In this example, I set up a $q.all() for promises one, two, and three which will get resolved at some random time. I then add promises onto the ends of one and three. I want the all to resolve when all the chains have been resolved. Here is the output when I run this code:

one done 
one doneChained
two done
three done
ALL PROMISES RESOLVED
three doneChained
three doneChainedChained 

Is there a way to wait for the chains to resolve?


Source: (StackOverflow)

Angular JS: how to bind to promises

I am trying to bind a promise to a view. I don't know if you can do that directly, but that's what I'm attempting to do. Any ideas what I am doing wrong?

Note: the source is a little contrived with the timeout and uses static data, but that's to make the code easier to diagnose.

EDIT: JSFiddle Page: http://jsfiddle.net/YQwaf/27/

EDIT: SOLUTION: It turned out you can directly bind promises. I had two problems with my original code:

  1. Using setTimeout() instead of angular's $timeout was a problem. Angular doesn't know it needs to refresh the UI when the timeout is triggered ( You could solve this with $scope.$apply inside setTimeout, or you can just use $timeout )
  2. Binding to a function that returned a promise was a problem. If it gets called a second time, it makes yet another promise. Better is to set a scope variable to the promise and only create a new promise as needed. (In my case, this was calling $scope.$watch on the Country Code)

HTML:

<div ng:controller="addressValidationController">
    Region Code <select ng:model="regionCode" ng:options="r.code as r.name for r in getRegions()"/>
    Country Code<select ng:model="countryCode"><option value="US">United States</option><option value="CA">Canada</option></select>
</div>

JS:

function addressValidationController($scope, $q) {
    var regions = {
        US: [{code: 'WI',name: 'Wisconsin'}, {code: 'MN',name: 'Minnesota'}], 
        CA: [{code: 'ON',name: 'Ontario'}]
    };
    $scope.getRegions = function () {
        var deferred = $q.defer();
        setTimeout(function () {
            var countryRegions = regions[$scope.countryCode];
            console.log(countryRegions);
            if(countryRegions === undefined) {
                deferred.resolve([]);
            } else {
                deferred.resolve(countryRegions);
            }
        }, 1000);
        return deferred.promise;
    };
}

Source: (StackOverflow)

How to Check Whether an Angular $q promise Is Resolved

I understand that typically one would just attach continuation code with a then() call and chain behavior when using promises. However, I want to kick off a promise-wrapped asynchronous call and then separately kick off a 3-second $timeout() so I can take a UI action, ONLY IF the original promise has not yet completed. (I anticipate that this would only happen on slow connections, mobile devices on 3G, etc.)

Given a promise, can I check whether it's complete or not without blocking or waiting?


Source: (StackOverflow)

Koa / Co / Bluebird or Q / Generators / Promises / Thunks interplay? (Node.js) [closed]

I'm investigating building a web app in part with Koa, but I don't quite have a handle on the hows, whens, and whys of choosing between - and applying - the range of supportive "making async easier" technologies/approaches (listed below).

Overall the disparate guidance on the web about this subject still leaves things blurry, especially in respect to evolving best practices, or at least better ones, and under what scenarios. There seems to be little or nothing on the web that puts it all in context.

I'm hoping the responses to this big arse sprawling post can correct that. Also maybe the questions below can inspire someone to write a thorough blog post or the like to address this matter. My sense is I'm not even close to the only one who would benefit from that.

So I'd be pleased if the bright community could help answer and provide clarity to the following questions in respect to the technologies listed below (in bold type):

-- a) How, and under what circumstance (as applicable) are they complements, supplements, substitutes, and/or overlapping solutions to one another?

-- b) What are their trade-offs in respect to speed-performance, error handling ease, and debugging ease?

-- c) When, where, and why may it be better to use "this" versus "that" technology, technologies-combo, and/or approach?

-- d) Which technologies or approaches, if any, may be "dimming stars".

(Hoping that the opinions that are part of answers can be well explained.)

==============================

Technologies:

* Koa *

My understanding:

Koa is a minimal foundation for build Node apps geared for taking advantage of ECMAScript-6 features, one feature in particular being generators.

* Co *

My understanding:

-- Co is a library of utilites for running ECMAScript-6 generators (which are native to Node .011 harmony), with the goal to allieve some/much(?) of the need to write boilerplate code for running and managing generators.

-- Co is intrinsically part of Koa(?).

Specific questions:

-- If and how does one use Co differently in Koa than in a non-Koa context. In other words, does Koa wholly facade Co?

-- Could Co be replaced in Koa with some other like generator library if there is/was a better one? Are there any?

* Promise Libraries such as "Q" and Bluebird *

My understanding:

-- They are in a sense "polyfills" for implmententing the Promises/A+ spec, if and until Node natively runs that spec.
-- They have some further non-spec convenience utilities for facilitating the use promises, such as Bluebird's promisfyAll utility.

Specific questions:

-- My understanding is the ECMAScript-6 spec does/will largely reflect the Promises/A+ spec, but even so, Node 0.11v harmony does not natively implement Promises. (Is this correct?) However when it does, will technologies such as Q and Bluebird be on their way out?

-- I've read something to the effect that "Q" and Bluebird support generators. What does this mean? Does it mean in part that, for example, they to some degree provided the same utility as Co, and if so to what degree?

* Thunks and Promises *

I think I have an fair handle on what they are, but hoping someone can provide a succinct and clear "elevator pitch" definition on what each is, and of course, as asked above, to explain when to use one versus the other -- in a Koa context and not in it.

Specific questions:

-- Pro and cons to using something like Bluebird's promisfy, versus say using Thunkify (github com/visionmedia/node-thunkify)?

==============================

To give some further context to this post and its questions, it might be interesting if Koa techniques presented in the following webpages could be discussed and contrasted (especiallly on a pros vs cons basis):

-- a) www.marcusoft . net/2014/03/koaintro.html (Where's the thunks or promises, or am I not seeing something?)

-- b) strongloop . com/strongblog/node-js-express-introduction-koa-js-zone (Again, where's the thunks or promises?)

-- c) github . com/koajs/koa/blob/master/docs/guide.md (What does the "next" argument equate to, and what set it and where?)

-- d) blog.peterdecroos . com/blog/2014/01/22/javascript-generators-first-impressions (Not in a Koa context, but presents the use of Co with a promise library (Bluebird), so I'm assuming the technique/pattern presented here lends itself to usage in Koa(?). If so, then how well?

Thanks all!


Source: (StackOverflow)

Futures vs. Promises

I'm confusing myself with difference between a future and a promise.

Obviously, they have different methods and stuff, but what is the actual use case?

Is it?:

  • when I'm managing some async task, I use future to get the value "in future"
  • when I'm the async task, I use promise as the return type to allow the user get a future from my promise

Source: (StackOverflow)

What does $.when.apply($, someArray) do?

I'm reading about Deferreds and Promises and keep coming across $.when.apply($, someArray). I'm a little unclear on what this does exactly, looking for an explanation that one line works exactly (not the entire code snippet). Here's some context:

var data = [1,2,3,4]; // the ids coming back from serviceA
var processItemsDeferred = [];

for(var i = 0; i < data.length; i++){
  processItemsDeferred.push(processItem(data[i]));
}

$.when.apply($, processItemsDeferred).then(everythingDone); 

function processItem(data) {
  var dfd = $.Deferred();
  console.log('called processItem');

  //in the real world, this would probably make an AJAX call.
  setTimeout(function() { dfd.resolve() }, 2000);    

  return dfd.promise();
}

function everythingDone(){
  console.log('processed all items');
}

Source: (StackOverflow)

Unit-test promise-based code in Angular

I'm having hard times trying to test promise-based code in Angular.

I have the following code in my controller:

    $scope.markAsDone = function(taskId) {
        tasksService.removeAndGetNext(taskId).then(function(nextTask) {
            goTo(nextTask);
        })
    };

    function goTo(nextTask) {
        $location.path(...);
    }

I'd like to unit-test the following cases:

  • when markAsDone is called it should call tasksService.removeAndGetNext
  • when tasksService.removeAndGetNext is done it should change location (invoke goTo)

It seems to me that there is no easy way to test those two cases separately.

What I did to test the first one was:

var noopPromise= {then: function() {}}
spyOn(tasksService, 'removeAndGetNext').andReturn(noopPromise);

Now to test second case I need to create another fake promise that would be always resolved. It's all quite tedious and it's a lot of boilerplate code.

Is there any other way to test such things? Or does my design smell?


Source: (StackOverflow)

Angularjs $q.all

I have implemented the $q.all in angularjs, but I can not make the code working. Here is my code :

UploadService.uploadQuestion = function(questions){

        var promises = [];

        for(var i = 0 ; i < questions.length ; i++){

            var deffered  = $q.defer();
            var question  = questions[i]; 

            $http({

                url   : 'upload/question',
                method: 'POST',
                data  : question
            }).
            success(function(data){
                deffered.resolve(data);
            }).
            error(function(error){
                deffered.reject();
            });

            promises.push(deffered.promise);
        }

        return $q.all(promises);
    }

And here is my controller which call the services:

uploadService.uploadQuestion(questions).then(function(datas){

   //the datas can not be retrieved although the server has responded    
}, 
function(errors){ 
   //errors can not be retrieved also

})

I think there is some problem setting up $q.all in my service. Any help really appreciated. Thank you.


Source: (StackOverflow)

Aren't promises just callbacks?

I've been developing JavaScript for a few years and I don't understand the fuss about promises at all.

It seems like all I do is change:

api(function(result){
    api2(function(result2){
        api3(function(result3){
             // do work
        });
    });
});

Which I could use a library like async for anyway, with something like:

api().then(function(result){
     api2().then(function(result2){
          api3().then(function(result3){
               // do work
          });
     });
});

Which is more code and less readable. I didn't gain anything here, it's not suddenly magically 'flat' either. Not to mention having to convert things to promises.

So, what's the big fuss about promises here?


Source: (StackOverflow)

Can you resolve an angularjs promise before you return it?

I am trying to write a function that returns a promise. But there are times when the information requested is available immediately. I want to wrap it in a promise so that the consumer doesn't need to make a decision.

function getSomething(id) {
    if (Cache[id]) {
        var deferred = $q.defer();
        deferred.resolve(Cache[id]); // <-- Can I do this?
        return deferred.promise;
    } else {
        return $http.get('/someUrl', {id:id});
    }
}

And use it like this:

somethingService.getSomething(5).then(function(thing) {
    alert(thing);
});

The problem is that the callback does not execute for the pre-resolved promise. Is this a legitimate thing to do? Is there a better way to handle this situation?


Source: (StackOverflow)

How do I access previous promise results in a .then() chain?

I have restructured my code to promises, and built a wonderful long flat promise chain, consisting of multiple .then() callbacks. In the end I want to return some composite value, and need to access multiple intermediate promise results. However the resolution values from the middle of the sequence are not in scope in the last callback, how do I access them?

function getExample() {
    return promiseA(…).then(function(resultA) {
        // some processing
        return promiseB(…);
    }).then(function(resultB) {
        // more processing
        return // how do I gain access to resultA here?
    });
}

Source: (StackOverflow)

What is the explicit promise construction antipattern and how do I avoid it?

I was writing code that does something that looks like:

function getStuffDone(param) {           | function getStuffDone(param) {
    var d = Q.defer(); /* or $q.defer */ |     return new Promise(function(resolve, reject) {
    // or = new $.Deferred() etc.        |     // using a promise constructor
    myPromiseFn(param+1)                 |         myPromiseFn(param+1)
    .then(function(val) { /* or .done */ |         .then(function(val) {
        d.resolve(val);                  |             resolve(val);
    }).catch(function(err) { /* .fail */ |         }).catch(function(err) {
        d.reject(err);                   |             reject(err);
    });                                  |         });
    return d.promise; /* or promise() */ |     });
}                                        | }

Someone told me this is called the "deferred antipattern" or the "Promise constructor antipattern" respectively, what's bad about this code and why is this called an antipattern?


Source: (StackOverflow)