EzDevInfo.com

promise

A lightweight implementation of CommonJS Promises/A for PHP.

What is std::promise?

I'm fairly familiar with the new standard library's std::thread, std::async and std::future components (e.g. see this answer), which are straight-forward.

However, I cannot quite grasp what std::promise is, what it does and in which situations it is best used. The standard document itself doesn't contain a whole lot of information beyond its class synopsis, and neither does just::thread.

Could someone please give a brief, succinct example of a situation where an std::promise is needed and where it is the most idiomatic solution?


Source: (StackOverflow)

jQuery deferreds and promises - .then() vs .done()

I've been reading about jQuery deferreds and promises and I can't see the difference between using .then() & .done() for successful callbacks. I know Eric Hynds mentions that .done() and .success() map to the same functionality but I'm guessing so does .then() as all the callbacks are all invoked on a completion of a successful operation.

Can anyone please enlighten me to the correct usage?

Many thanks


Source: (StackOverflow)

Advertisements

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)

Why are callbacks more "tightly coupled" than promises?

Can you explain me the following phrase (taken from an answer to Stack Overflow question What are the differences between Deferred, Promise and Future in Javascript?)?

What are the pros of using jQuery promises against using the previous jQuery callbacks?

Rather than directly passing callbacks to functions, something which can lead to tightly coupled interfaces, using promises allows one to separate concerns for code that is synchronous or asynchronous.


Source: (StackOverflow)

Understanding promises in node.js

From what I have understood there are three ways of calling asynchronous code:

  1. Events: eg. request.on("event"), callback);
  2. Callbacks: eg. fs.open(path, flags, mode, callback);
  3. Promises

I found a promise library https://github.com/kriszyp/node-promise but I don't get it.

Could someone explain what promises are all about and why I should use it?

Also, why was it removed from Node.js?


Source: (StackOverflow)

How do Clojure futures and promises differ?

Both futures and promises block until they have calculated their values, so what is the difference between them?


Source: (StackOverflow)

Difference between Future and Promise

What's the difference between future and promise?
They both act like a placeholder for future results, but where is the main difference?


Source: (StackOverflow)

How is a promise/defer library implemented?

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)

What are the differences between Deferred, Promise and Future in Javascript?

What are the differences between Deferreds, Promises and Futures? Is there a generally approved theory behind all these three?


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)

Native Support for Promises in Node.js

Is there native support for promises in current versions of Node.js?

Node.js uses the V8 engine. This JavaScript engine is also used by Chrome, and Chrome 32 has native support for promises. But I can't seem to get promises to work (natively) in Node.js.

I've tried the following code in Chrome 32 and it works.

var promise = new Promise(function(resolve, reject) {
  // do a thing, possibly async, then…

  if ( 1===1 /* everything turned out fine */) {
    resolve("Stuff worked!");
  }
  else {
    reject(Error("It broke"));
  }
});

promise.then(function( message ) {
  console.log( message );
},
function( err ) {
  console.log( err );
});

However, when I try this same code in Node.js, I get:

var promise = new Promise(function(resolve, reject) {
                   ^
ReferenceError: Promise is not defined

This code is from the excellent tutorial:

http://www.html5rocks.com/en/tutorials/es6/promises/


Source: (StackOverflow)

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)

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)

Angularjs $http.get().then and binding to a list

I have a list that looks like this:

<li ng-repeat="document in DisplayDocuments()" ng-class="IsFiltered(document.Filtered)">
    <span><input type="checkbox" name="docChecked" id="doc_{{document.Id}}" ng-model="document.Filtered" /></span>
    <span>{{document.Name}}</span>
</li>

I bind this list in my controller, to this:

$scope.Documents = $http.get('/Documents/DocumentsList/' + caseId).then(function(result) {
    return result.data;
});

When this runs, I dont get any results. when I remove the then method, I get three empty lines, making the count OK, but no information is displayed.

I know "everthing" else works, since I previously populated the list with jQuery, what am I doing wrong?

Here's the response from the server:

{Id:3f597acf-a026-45c5-8508-bc2383bc8c12, Name:ZZ_BL0164_Skisse BL0164_945111.pdf, Order:1,…}
{Id:46f51f1f-02eb-449a-9824-8633e8ae7f31, Name:ZB_BL0201_Firmaattest BL0201_945111.pdf, Order:1,…}
{Id:fddd1979-c917-4b32-9b83-b315f66984ed, Name:ZA_BL0228_Legitimasjonsskjema BL0228_945111.pdf,…}

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)