EzDevInfo.com

q

A tool for creating and composing asynchronous promises in JavaScript kriskowal/q

How does Angular $q.when work?

Can some one explain me how does $q.when work in AngularJs? I'm trying to analyze how $http work and found this:

var promise = $q.when(config);

And here is config object from Chrome console:

Object {transformRequest: Array[1], transformResponse: Array[1], cache: Object, method: "GET", url: "/schedule/month_index.html"…}
cache: Object
headers: Object
method: "GET"
transformRequest: Array[1]
transformResponse: Array[1]
url: "/schedule/month_index.html"
__proto__: Object

What happens next? How this object get's resolved or rejected?


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)

Advertisements

javascript promise not passing all arguments (using Q)

I am having trouble passing all arguments. My promise callback only receives one instead of three:

var asyncFunction= function(resolve) {
    setTimeout(function() {
        resolve("Some string that is passed", "and another", "third");
    }, 1000);
};

var promiseFunction = function () {
    var deferred = Q.defer();

    asyncFunction(deferred.resolve);

    return deferred.promise;
};

promiseFunction().then(function() {
    // Only one argument is passed here instead of 3
    // { '0': 'Some string that is passed' }
    console.log(arguments); 
});

Any idea what I am doing wrong?


Source: (StackOverflow)

While loop with promises

What would be the idiomatic way to do something like a while loop with promises. So:

do something if the condition still stands do it again repeat then do something else.

dosomething.then(possilblydomoresomethings).then(finish)

I've done it this way I was wondering if there were any better/more idomatic ways?

var q = require('q');

var index = 1;

var useless =  function(){
        var currentIndex = index;
        console.log(currentIndex)
        var deferred = q.defer();
        setTimeout(function(){
            if(currentIndex > 10)
                deferred.resolve(false);
            else deferred.resolve(true);
            },500);
        return deferred.promise;
    }

var control = function(cont){
        var deferred = q.defer();
        if(cont){
                index = index + 1;
                useless().then(control).then(function(){
                        deferred.resolve();
                    });
            }
         else deferred.resolve();
        return deferred.promise;
    }

var chain = useless().then(control).then(function(){console.log('done')});

Output: 1 2 3 4 5 6 7 8 9 10 11 done


Source: (StackOverflow)

Replacing callbacks with promises in Node.js

I have a simple node module which connects to a database and has several functions to receive data, for example this function:


dbConnection.js:

var mysql = require('mysql');
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'user',
    password: 'password',
    database: 'db'
});

exports.getUsers = function (callback) {
    connection.connect(function () {
        connection.query('SELECT * FROM Users', function (err, result) {
            if(!err){
                callback(result);
            }
        });
    });
};

The module would be called that way from a different node module:


app.js:

var dbCon = require('./dbConnection.js');
dbCon.getUsers(console.log);

I would like to use promises instead of callbacks in order to return the data. So far I've read about nested promises in the following thread: Writing Clean Code With Nested Promises, but I couldn't find any solution that is simple enough for this use case. What would be the correct way to return result using a promise? I'd like to use the q node module for that.


Source: (StackOverflow)

angular $q, How to chain multiple promises within and after a for-loop

I want to have a for-loop which calls async functions each iteration.

After the for-loop I want to execute another code block, but not before all the previous calls in the for-loop have been resolved.

My problem at the moment is, that either the code-block after the for-loop is executed before all async calls have finished OR it is not executed at all.

The code part with the FOR-loop and the code block after it (for complete code, please see fiddle):

[..]
function outerFunction($q, $scope) {
    var defer = $q.defer();    
    readSome($q,$scope).then(function() {
        var promise = writeSome($q, $scope.testArray[0])
        for (var i=1; i < $scope.testArray.length; i++) {
             promise = promise.then(
                 angular.bind(null, writeSome, $q, $scope.testArray[i])
             );                                  
        } 
        // this must not be called before all calls in for-loop have finished
        promise = promise.then(function() {
            return writeSome($q, "finish").then(function() {
                console.log("resolve");
                // resolving here after everything has been done, yey!
                defer.resolve();
            });   
        });        
    });   

    return defer.promise;
}

I've created a jsFiddle which can be found here http://jsfiddle.net/riemersebastian/B43u6/3/.

At the moment it looks like the execution order is fine (see the console output).

My guess is, that this is simply because every function call returns immediately without doing any real work. I have tried to delay the defer.resolve with setTimeout but failed (i.e. the last code block was never executed). You can see it in the outcommented block in the fiddle.

When I use the real functions which write to file and read from file, the last code block is executed before the last write operation finishes, which is not what I want.

Of course, the error could be in one of those read/write functions, but I would like to verify that there is nothing wrong with the code I have posted here.


Source: (StackOverflow)

Problems inherent to jQuery $.Deferred (jQuery 1.x/2.x)

@Domenic has a very thorough article on the failings of jQuery deferred objects: You're missing the Point of Promises. In it Domenic highlights a few failings of jQuery promises in comparison to others including Q, when.js, RSVP.js and ES6 promises.

I walk away from Domenic's article feeling that jQuery promises have an inherent failing, conceptually. I am trying to put examples to the concept.

I gather there are two concerns with the jQuery implementation:

1. The .then method is not chainable

In other words

promise.then(a).then(b)

jQuery will call a then b when the promise is fulfilled.

Since .then returns a new promise in the other promise libraries, their equivalent would be:

promise.then(a)
promise.then(b)

2. The exception handling is bubbled in jQuery.

The other issue would seem to be exception handling, namely:

try {
  promise.then(a)
} catch (e) {
}

The equivalent in Q would be:

try {
  promise.then(a).done()
} catch (e) {
   // .done() re-throws any exceptions from a
}

In jQuery the exception throws and bubbles when a fails to the catch block. In the other promises any exception in a would be carried through to the .done or .catch or other async catch. If none of the promise API calls catch the exception it disappears (hence the Q best-practice of e.g. using .done to release any unhandled exceptions).

 

Do the problems above cover the concerns with the jQuery implementation of promises, or have I misunderstood or missed issues?


Edit This question relates to jQuery < 3.0; as of jQuery 3.0 alpha jQuery is Promises/A+ compliant.


Source: (StackOverflow)

Define empty Bluebird promise like in Q

With Q I can define a new promise with:

var queue = q();

But with Bluebird if I do:

var queue = new Promise();

I get:

TypeError: the promise constructor requires a resolver function

How can I get the same result that I had with Q?

This is a snippet of my code:

var queue    = q()
    promises = [];
queue = queue.then(function () {
    return Main.gitControl.gitAdd(fileObj.filename, updateIndex);
});
// Here more promises are added to queue in the same way used above...
promises.push(queue);
return Promise.all(promises).then(function () {
   // ...
});

Source: (StackOverflow)

How to use "q" module for refactoring mongoose code?

I'm using mongoose to insert some data into mongodb. The code looks like:

var mongoose = require('mongoose');
mongoose.connect('mongo://localhost/test');
var conn = mongoose.connection;

// insert users
conn.collection('users').insert([{/*user1*/},{/*user2*/}], function(err, docs) {
    var user1 = docs[0], user2 = docs[1];

    // insert channels
    conn.collection('channels').insert([{userId:user1._id},{userId:user2._id}], function(err, docs) {
        var channel1 = docs[0], channel2 = docs[1];

        // insert articles
        conn.collection('articles').insert([{userId:user1._id,channelId:channel1._id},{}], function(err, docs) {
            var article1 = docs[0], article2 = docs[1];

        }
    });
};

You can see there are a lot of nested callbacks there, so I'm trying to use q to refactor it.

I hope the code will look like:

Q.fcall(step1)
.then(step2)
.then(step3)
.then(step4)
.then(function (value4) {
    // Do something with value4
}, function (error) {
    // Handle any error from step1 through step4
})
.end();

But I don't know how to do it.


Source: (StackOverflow)

How to properly abort a node.js promise chain using Q?

I'm using the Q module for Node.js in attempts to avoid the "pyramid of doom" in scenarios where I have many steps. For example:

function doTask(task, callback)
{
    Q.ncall(task.step1, task)
    .then(function(result1){
        return Q.ncall(task.step2, task);
    })
    .then(function(result2){
        return Q.ncall(task.step3, task);
    })
    .fail(callback).end();
}

Essentially this seems to work; if an error is thrown by any of the task steps, it is passed to the callback (though I would be welcome to improvements, as I am new to node.js promises). However, I have a problem when I need to abort the task-chain early. For example, if result1 is successfully returned I might want to call the callback early and abort the rest, but my attempts to do so are failing...

function doTask(task, callback)
{
    Q.ncall(task.step1, task)
    .then(function(result1){
        if(result1)
        {// the rest of the task chain is unnecessary 
            console.log('aborting!');
            callback(null, result1);
            return null;
        }
        return Q.ncall(task.step2, task);
    })
    .then(function(result2){
        console.log('doing step 3...');
        return Q.ncall(task.step3, task);
    })
    .fail(callback).end();
}

In this example, I see both "aborting!" and "doing step 3..." printed.

I'm sure I'm merely misunderstanding some basic principles here, so would appreciate any help. Thanks!


Source: (StackOverflow)

Unhandled rejection reasons (should be empty)

I'm getting into promises pattern with Q and I keep getting warning "[Q] Unhandled rejection reasons (should be empty)" in console. What em I doing wrong?

http://jsfiddle.net/FpyDr/1/

function load(url) {
    var deferred = Q.defer();

    $.ajax({
        type: "GET",
        processData: false,
        dataType: "html",
        url: url,
        cache: false
    }).done(function (response, status, xhr) {

        deferred.reject(new Error("test error"));

        return;
    }).fail(function (xhr, status, error) {

        deferred.reject(new Error("ajax failed"));

        return;
    });

    return deferred.promise;
}

load("http://fiddle.jshell.net")
    .then(function (result) {
        console.log("got result", typeof(result));
    })
    .catch(function (error) {
        console.log("got error", error);
        return true;
    })
    .done();

Source: (StackOverflow)

Can I make a synchronous promise in the JavaScript Q library?

I want to do something like the following:

delay( 2500 )
  .then( function () { console.log( "Step 1 done" ) } )
  .then( delay( 7500 ) )
  .then( function () { console.log( "Step 2 done" ) } );

So implementation of delay has been demonstrated many times before:

function delay( ms ) {
  var deferred = Q.defer();
  setTimeout( deferred.resolve, ms );
  return deferred.promise;
}

But if I run the above in node.js I get:

... delay of 2500ms
Step 1 done
Step 2 done
... delay of ~7500ms

rather than what I expect to see:

... delay of 2500ms
Step 1 done
... delay of 7500ms
Step 2 done

In the examples provided on https://github.com/kriskowal/q/wiki/Examples-Gallery I can't find any examples of synchronous functions (functions that return a value without any callbacks involved) chained with promise functions.

Any ideas how to mix in synchronous actions with asynchronous promises?

I've tried:

function synchronousPromise() {
  var deferred = Q.defer();
  console.log( "Synchronous function call" );
  deferred.resolve();
  return deferred.promise;
}

delay( 2500 )
  .then( function(){synchronousPromise()} )
  .then( function(){delay( 7500 )} )
  .then( function(){synchronousPromise()} );

And this outputs:

... delay of 2500ms
Time now is 2013-06-20
Time now is 2013-06-20
... delay of 7500ms

.. still not what I'm trying to achieve.


Source: (StackOverflow)

Q 2.0.0 installed with Bower causes Uncaught ReferenceError: require is not defined

I am using Q in a project, and I am using bower to manage my JS dependencies. I am including Q 2.0.0 with bower in bower.json

"dependencies" : {
    "q": "~2.0.0"
}

In my index.html, I include Q with a script tag

<script src="bower_components/q/q.js"></script>

When I load the page, I see in the console:

Uncaught ReferenceError: require is not defined q.js:43

Line 43 of q.js:

require("collections/shim");

What am I missing here? Should I be using Browserify or require.js to get this to work? I expected the library to be accessible by simply using a tag.


Source: (StackOverflow)

AngularJS Promises, $q, defer

EDIT

The first answer is the elegant one, but, as stated a few times in this question and another questions on stackoverflow, the problem is that the service and the controller run their thing before the data actually arrives.

(Last comment on the first answer:)

Yes, the problem is that the API calls finish AFTER the service runs and returns everything to the controller, see here screencast.com/t/uRKMZ1IgGpb7 ... That's my BASE question, how could I wait on all the parts for the data to arrive?

It's like I'm saying it on repeat, how do we make a service that populates the array after the successful data retrieval, and the controller getting data after all this happens, because as you can see in my screenshot, things run in a different order.


I have this code:

 var deferred = $q.defer();
            $http.get('../wordpress/api/core/get_category_posts/?category_id=14 ').success(function(data) {
                //we're emptying the array on every call
                theData = [];
                catName = data.category.slug;
                theData = data;
                theData.name = catName;
                aggregatedData.push(theData);
            });
            $http.get('../wordpress/api/core/get_category_posts/?category_id=15 ').success(function(data) {
                theData = [];
                catName = data.category.slug;
                theData = data;
                theData.name = catName;
                aggregatedData.push(theData);
            });
            $http.get('../wordpress/api/core/get_category_posts/?category_id=16 ').success(function(data) {
                theData = [];
                catName = data.category.slug;
                theData = data;
                theData.name = catName;
                aggregatedData.push(theData);
            });
            $http.get('../wordpress/api/core/get_category_posts/?category_id=17 ').success(function(data) {
                theData = [];
                catName = data.category.slug;
                theData = data;
                theData.name = catName;
                aggregatedData.push(theData);
            });
            //deferred.resolve(aggregatedData);
            $timeout(function() {
                deferred.resolve(aggregatedData);
            }, 1000);
            /*//deferred.reject('There is a connection problem.');
            if (myservice._initialized) {
                $rootScope.$broadcast('postsList', deferred.promise);
            }*/
            //myservice._initialized = true;
            myservice = deferred.promise;
            return deferred.promise;

For the life of me I can't understand why do I have to put a timeout when passing the resulting array to defer ?

Shouldn't the principle be like, defer waits for the information to come and then returns the promise? What is the point of that 1 second there? From what I understand defer should be able to wait as long as needed for the API to return the result and the return the promised data.

I'm really confused, I've banged my head against the walls for the last two hours because I was not receiving any data in my controller, only when I put that timeout there.


Source: (StackOverflow)

Node.js Asynchronous Library Comparison - Q vs Async

I have used kriskowal's Q library for a project (web scraper / human-activity simulator) and have become acquainted with promises, returning them and resolving/rejecting them, and the library's basic asynchronous control flow methods and error-throwing/catching mechanisms have proven essential.

I have encountered some issues though. My promise.then calls and my callbacks have the uncanny tendency to form pyramids. Sometimes it's for scoping reasons, other times it's to guarantee a certain order of events. (I suppose I might be able to fix some of these problems by refactoring, but going forward I want to avoid "callback hell" altogether.)

Also, debugging is very frustrating. I spend a lot of time console.log-ing my way to the source of errors and bugs; after I finally find them I will start throwing errors there and catching them somewhere else with promise.finally, but the process of locating the errors in the first place is arduous.

Also, in my project, order matters. I need to do pretty much everything sequentially. Oftentimes I find myself generating arrays of functions that return promises and then chaining them to each other using Array.prototype.reduce, which I don't think I should have to do.

Here is an example of one of my methods that uses this reduction technique:

removeItem: function (itemId) {

  var removeRegexp = new RegExp('\\/stock\\.php\\?remove=' + itemId);

  return this.getPage('/stock.php')
  .then(function (webpage) {
    var
      pageCount = 5,
      promiseFunctions = [],
      promiseSequence;

    // Create an array of promise-yielding functions that can run sequentially.
    _.times(pageCount, function (i) {
      var promiseFunction = function () {
        var
          promise,
          path;

        if (i === 0) {
          promise = Q(webpage);
        } else {
          path = '/stock.php?p=' + i;
          promise = this.getPage(path);
        }

        return promise.then(function (webpage) {
          var
            removeMatch = webpage.match(removeRegexp),
            removePath;

          if (removeMatch !== null) {
            removePath = removeitemMatch[0];

            return this.getPage(removePath)
            .delay(1000)
            // Stop calling subsequent promises.
            .thenResolve(true);
          }

          // Don't stop calling subsequent promises.
          return false;

        }.bind(this));
      }.bind(this);

      promiseFunctions.push(promiseFunction);
    }, this);

    // Resolve the promises sequentially but stop early if the item is found.
    promiseSequence = promiseFunctions.reduce(function (soFar, promiseFunction, index) {
      return soFar.then(function (stop) {
        if (stop) {
          return true;
        } else {
          return Q.delay(1000).then(promiseFunction);
        }
      });
    }, Q());

    return promiseSequence;
  }.bind(this))
  .fail(function (onRejected) {
    console.log(onRejected);
  });
},

I have other methods that do basically the same thing but which are suffering from much worse indentation woes.

I'm considering refactoring my project using coalan's async library. It seems similar to Q, but I want to know exactly how they differ. The impression I am getting is that async more "callback-centric" while Q is "promise-centric".

Question: Given my problems and project requirements, what would I gain and/or lose by using async over Q? How do the libraries compare? (Particularly in terms of executing series of tasks sequentially and debugging/error-handling?)


Source: (StackOverflow)