Menu
  • HOME
  • TAGS

Require inside Q promise

javascript,requirejs,q

You need to get require to work with a promise, otherwise you have two independent asynchronous systems. I didn't test, but something like this should work: Q.fcall(function () { console.log('1'); }).then(function () { var deferred = Q.defer(); console.log('2'); require(['myfile'], function (myfile) { console.log('2.1'); deferred.resolve(myfile); }); return deferred.promise; }).then(function (myfile) {...

Handling Errors in A Chain of Promises

javascript,promise,q

You can use multiple catch blocks, like this function X() { return Q.Promise(function(resolve, reject) { return Users.find() .catch(function(err) { // Handle user finding error throw new Error("Problem in finding users"); }) .then(function(user) { return Q.all([ getUserProfileInfo(user), getUserSomethingElse(user) ]); }) .spread(function(profile, something) { // do stuff resolve(); }) .catch(function(err) { reject();...

Log all reject promises in Q

node.js,promise,q

Q actually already supports this - as of 1.3.0 Q offers the standard unhandled rejection hooks: process.on("unhandledRejection", function(reason, p) { console.log("Unhandled rejection detected ", reason, p); }); You can also log caught errors from .done with Q.onerror: Q.onerror = function(error){ // errors will be here and not thrown in `done`...

Q: Promisify Synchronous operations for chaining promises?

promise,q,chaining

No, moreover, it gives the false impression that these methods are async so you or other developers might call them and expect that the method is not undermining the entire io.js/node.js concurrency model by performing sync IO. I recommend that you either make these functions not return promises or make...

KDB+ / Q table creation with foreign key

database,table,foreign-keys,q,kdb

You can use the same syntax on the column values list: q)T3:1!flip ((`id`f1 )!((1 2 3 4 5);(`T1$2 2 2 4 4))) q)T3~T2 1b Update: Again for this case we can use the same syntax on the list - q)A:enlist`T1$1 2 3 4 5 q)meta flip (`id`v1`v2)!(B,A) c | t...

call functions in async with node which is more recomended Q or callback

javascript,node.js,callback,promise,q

I don't even see why you particularly need promises for this. function myHandler(req, res) { var dataChunks = [], dataRaw, data; req.on("data", function (chunk) { dataChunks.push(chunk); }); req.on("end", function () { dataRaw = Buffer.concat(dataChunks); data = dataRaw.toString(); console.log(data); var filePath = 'C://test.txt'; var writeStream = fs.createWriteStream(filePath, {flags: 'w'}); writeStream.write(data); writeStream.on('finish',...

Q promise .then() undefined

javascript,node.js,q

Something like this should do it ("should", because I have no way to test it with MySQL) var Q = require('Q'); function DB(pool) { this.asyncQuery = function(sql) { return function () { var result = Q.defer(), paramsArray = [].slice.call(arguments); pool.getConnection(function(err, con) { if (err) result.thenReject(err); con.query(sql, paramsArray, result.makeNodeResolver()); }); return...

Very random behaviour in Node with gm, buffers and promises

node.js,buffer,q,graphicsmagick

This section is incorrect: uploader = s3Client.putBuffer( buf, type + "/" + image.hash + "-orig" + image.extension, { 'Content-Length': buf.length, 'Content-Type': 'image/jpeg' }, function ( err, result ) { if ( err ) return reject( new Error( err ) ) if ( result.statusCode == 200 ) { image.orig = uploader.url...

How can I avoid breaking a promise chain when using q.map?

node.js,promise,q

You don't have an array of promises, you have an array of undefined values (and Q.all didn't warn you about it): Your mapper function is not returning anything. You're missing a return statement there: var promises = geese.map(function(goose) { return determineGooseType(goose.details) //^^^^^^ .then(function(type) { return recordNewGooseType(type) }) .then(function(dbInsertResult) { //...

AngularJS $q.all how to resolve data in service and not in controller

angularjs,service,factory,q

In your case myService.getDataN() is not a promise. Every getDataN should also return data inside then. ... function getData1() { return myHttpService.apiPromise($http.get('/api/data_1')).then(function(data1){ MyData.data1 = data1; return data1; }); } ... ...

Collection data from different pages for a list of data and sending them together

javascript,arrays,node.js,q

There is a minor mistake in your code that is getEventsOfMotion is not returning promise, replace it with following one: function getEventsOfMotion(publisher){ var defer = q.defer(); if(publisher.motion !== undefined){ //console.log('motion') url = 'https://example.com/v2/feeds/'+publisher.motion+'/events/?page='; publisher.motionEvent = [] getAllDataOfEvents(1,url,'M',publisher).then(function(test){ allProducts.push(test); defer.resolve(); //console.log(test) }) }else{ console.log('yes') } return defer.promise() } Happy Helping!...

How can I resolve a $q.all in my controller in a Karma unit test?

angularjs,q,karma-jasmine

You're hiding the $rootScope variable of your test suite by declaring it as an argument of your test function. That's why it's undefined: jasmine calls the test functions withput any argument. Replace it('should redirect to a patient view if a cookie is set', function($rootScope) { by it('should redirect to a...

Collection data from different API and sending them all together in a response

javascript,node.js,q

Its one change required only. return getAllNodeData(currentPage,url,key) replace above line in getAllNodes with following one, and all will go okay getAllNodeData(currentPage,url,key).then(function(){ deferred.resolve(allProducts) }); Happy Helping!...

Node.js and Q Promises: How can I hand over parameters in a cleaner way?

javascript,node.js,coding-style,promise,q

To use Q.all in the desired way you'd have to do the following: function example(data) { return Q.all[ asyncFnOne().then(asyncFnTwo), data ]).spread(asyncFnThree); } Or use a variable for the first part of the chain, so that you don't have to stuff everything in one expression and could use return Q.all([promiseTwo, data])…....

How to start using $q?

angularjs,q

You need to inject it as well as add it to your argument list: app.controller('NodeCtrl', ['Tree', '$scope', '$element', '$q', function(Tree, $scope, $element, $q) { ...

in node, using Q, make 2 functions work in parallel but wait only for the first one to fulfill its promise

javascript,node.js,workflow,promise,q

I would have done so: var parallelWrapper = function(input) { var fastPromise = fastComputation(); var slowPromise = slowComputation() .then(function(data) { return makeSomething(); }) .then(function(data) { return makeSomethingElse(); }).catch(console.error); return Q([fastPromise, slowPromise]).all(); } And second example somthing like this: var myLongChainOfFunctions = function() { return firstFunction(someParams) .then(secondFunction) .then(thirdFunction) /*...*/ .then(parallelWrapper) /*...*/...

Angular $q.all() console.log output order timing not making sense to me

angularjs,q

$q.all expects an array of promises, the mentioned code makes it an array of array of promises xhrService.push([getEstimatedExpenseTypes]); pushes an array [getEstimatedExpenseTypes] into the array var promises = []; replacing xhrService.push([getEstimatedExpenseTypes]); with xhrService.push(getEstimatedExpenseTypes); makes the right ordering of execution. working fiddle EDIT if you want to push array of promises...

How to add Promise to event handler in javascript

javascript,node.js,promise,amqp,q

You're calling your functions immediately, rather than passing a function reference to the .then() handlers. .then() takes a function reference, not a promise as an argument. Change to this: Sender.prototype.connect_ = function() { return this.createConnection_() .then( this.connectionReady_.bind(this) ) .then( this.createExchange_.bind(this) ) .then( this.exchangeReady_.bind(this) ) .catch( function(err) { console.info( err );...

Node.js with typescript require and .d.ts files

javascript,node.js,typescript,q

Duplicate identifier 'Q' In the absence of an import or an export statement at the root of your file: Your file as well as any other such file passed to the TypeScript compiler is considered a part of the global namespace. So the variable Q is conflicting with the...

Is there a javascript promise library that handles runtime errors?

parse.com,promise,q,bluebird

It is simply impossible for a library to handle errors beyond its control. The only reason promise libraries are throw safe is because promises use return values to assimilate other promises. If all your code returns promises instead of callbacks, All A+ promise libraries (that's Q and Bluebird in your...

type char to type num mapping

q,kdb

You can use .Q.t. q).Q.t abs type `test "s" q).Q.t abs type 5i "i" Edit: Or even better just use .Q.ty This seems to return upper case for atoms and lower case for lists. q).Q.ty `test "S" q).Q.ty `test`test2 "s" ...

Getting values within a nest for-loop - node.js, javascript, redis, Q library

javascript,node.js,for-loop,redis,q

node.js is generally non-blocking, this is why callbacks are used. The callback passed to .hgetall will only execute when the data from redis has been fully received. The rest of the code around it will execute immediately and not wait for the data from redis. In fact, since the .hgetall...

How can I use Q-lib with restify in Nodejs

node.js,asynchronous,q,restify

I run your code, and get same error: /tmp/test.js:37 .then(function(request) { ^ TypeError: Cannot call method 'then' of undefined at Object.<anonymous> (/tmp/test.js:37:6) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:902:3 Then I add return deffered.promise; in the end...

Function Returns a Promise, Check Errors

javascript,promise,q

Well, this is going to a be a bummer. You can't While a lot of promise libraries let you do this and will report unhandled rejections for you - in Q you have no methods to automatically detect these failures. You have to Use .done or change a promise library....

What does “Promise fires on the same turn of the event loop” mean?

javascript,node.js,q

Basically, the point is that the promise's then handler will not run before the current flow of code has finished executing and control is returned to the execution environment (in this case Node). This is an important characteristic of Promises/A+ compliant promises because it ensures predictability. Regardless of whether the...

node js calling same deferred function from client and another node module

javascript,node.js,express,q

You can basically call getFilesFunc from getFiles: exports.getFilesFunc = function(payload){ return Q.nfcall(glob, payload.globPattern, payload.globOptions); }; exports.getFiles = function(req,res){ this.getFilesFunct(req.body).then(function(files) { res.send({success:true, data:files}); }, function(err) { res.status(400); winston.log('error', err); return res.send({success:false, reason: err}); }); }; ...

KDB+ / Q Better webinterface

q,kdb,web-interface

Have you tried doth package by simon? This is probably not even close to what you describe, but it could be a starting point to implement something custom.

How can I use `Q.set`?

javascript,promise,q

The Q.set is used to augment an object, in the future and it doesn't return the augmented object (in fact, it doesn't return anything at all). That is why you are getting undefined in the console.log. You need to use it like this var obj = { foo: "bar" };...

how to check error in qunit

javascript,qunit,q

There are lots of problems here. For one, you don't have any way to let the calling code know that your function has finished. Without that, QUnit can't determine when to run the assertions. Then you'll need to use QUnit's async ability, otherwise the test function finishes before your promise...

How to write a function with arguments using promises in Node.js?

javascript,node.js,promise,q

The arguments for only should go where they always went, just as well as those to find. It's only run that you want to call with a callback and get a promise out: Q.nfcall(Person.find({ surname: "Doe" }).only("name", "surname").run) .then(function(people){…}, function(err) {…}); But probably you'll have to use Q.ninvoke anyway: Q.ninvoke(Person.find({...

Chaining functions that return arrays of promises

javascript,node.js,promise,q

Q.all(returns_a_promise()) .then(returns_array_of_promises).all() .then(returns_another_array_of_promises).all() .then(yet_another_array_o_promises).all() .then(function () { logger.info("yea we done"); }); ...

How do you properly return multiple values from a promise?

javascript,promise,q

You can't resolve a promise with multiple properties just like you can't return multiple values from a function. A promise conceptually represents a value over time so while you can represent composite values you can't put multiple values in a promise. A promise inherently resolves with a single value -...

Type error when chaining Q.ninvoke

node.js,mongodb,q

TL;DR version: When called in a chain as opposed to directly as Q.ninvoke() the object whose function is to be invoked comes from the result of the prior function in the chain, not from the first parameter to the qpromise.ninvoke() call. Elaboration: While I initially thought from a quick glance...

angularjs return another promise in $q.all

angularjs,q,angular-promise

To add to my comments: .factory('WebSrvs', function($http,DatabaseSrvs) { var getData = function() { var promiseReceiverUrl = DatabaseSrvs.getLocalValue('value1'); var promiseVehicleId = DatabaseSrvs.getLocalValue('value2'); return $q.all([promiseReceiverUrl,promiseVehicleId]).then(function(results) { if(results[0].rows.length > 0 && results[1].rows.length > 0) { var v1 = results[0].rows.item(0).Value; var v2 = results[1].rows.item(0).Value; var req = { method: 'POST', url: v1, headers: {...

$q one function to handle both success and callback

angularjs,q

The answer is no, although if you want to run common code regardless of the result of your promise you can use finally

what is the benefit to use Q defer?

javascript,promise,q

One of the main authors of the Q library has written an article stating that Q.defer() is unnatural and outdated (although it does still have some practical applications). The more modern approach (which is what the article is about) is the revealing constructor pattern. This is also the approach that...

KDB+ / Q Accessing root namespace from namespace

namespaces,q,kdb

Context (namespace) is just a dictionary so you can use dictionary syntax. q) \d .seed q.seed) `.[`n] Reference: http://code.kx.com/wiki/JB:QforMortals/workspace_organization Check section: A Context is a Dictionary ...

.then .done promises not working in durandal spa using knockout and js

jquery,knockout.js,single-page-application,q,durandal-2.0

What if you let getSearchResult return a promise? var getSearchResult = function (dataHolder,text) { //return $.getJSON('/Api/Data/GetSearchItem/' + text).done(); jQuery.support.cors = true; return $.ajax({ url: '/Api/Data/GetItem/' + text, type: 'GET', dataType: 'json' }).then(function(data) { dataHolder(data); var check = dataHolder(); return dataHolder(); }); }; Then also let search return that some promise:...

Q.ninvoke replacement in node bluebird

node.js,mongoose,promise,q,bluebird

Well, there are several things you can do. The most obvious is surprisingly "nothing". Mongoose already returns Promises/A+ promises when you don't pass exec its callback, you can just assimilate them: repo.count = function(entity,query) { // entity is a mongoose model return entity.find(query).count().exec(); // return promise }; You can safely...

How to show exceptions on unhandled errors in Q promises

q

Apparently this is a limitation of Q. In order to make error handling slightly more verbose, there is the method .done(), which should be called after all other handlers and performs error reporting, similarly to the snippet I posted in my question. This is less than perfect because it requires...

$q.defer() not working with Angular service

javascript,angularjs,q

There is no need to use a $q.defer unless you are converting a non-promise based API with callbacks into a promise-based API (and even then, it is recommended to use $q(function(resolve, reject){...})). $http already returns a promise - just return that (or a chained .then promise); var httpResponsePromise = $http.get(url);...

Performance impact of or-ing Q objects in django query

python,sql,django,q

Was able to shrink down the length of the query significantly by reducing the number of of Qobjects. They were all of the format like: q1 = Q(field1=field1_val1, field2=field2_val1) q2 = Q(filed1=field1_val2, field2=field2_val2) #...etc I ended up grouping them by field1 values: q_dict = {field1_val1: [all field_2 values paired with...

AngularJS: Avoid calling same REST service twice before response is received

javascript,angularjs,http,asynchronous,q

Yes, all you need to do is to cache the promise and clean it off after the request is done. Any subsequent request in between can just use the same promise. angular.module("demo").factory("restService", ["$http", "$q", function($http, $q) { var _cache; return { get: function() { //If a call is already going...

q promise resolved before completed?

angularjs,q

Just use $http promise: factory.loadLayout = function (layoutName) { return $http.get('/api/getlayout/'+layoutName) .success(function (data) { layout = data; console.log("Got " + layout.name); resolve('OK'); }) .error(function(data,status,headers,config){ reject(new Error( status)); }); } And then to use it... factory.loadLayout(param).then(function (response) { ... }); OR I see what you are trying to do. Instead create...

Variable context issue on node.js using Q (promise) [duplicate]

javascript,node.js,promise,q

The answer of the following question is also working in this case. How do I pass the value (not the reference) of a JS variable to a function? My loop is now: var promises= []; for (var i = 3 ; i >= 3 ; i--) { log.debug('-'+i); (function (i)...

Sharing promises between modules vs having multiple promises

javascript,node.js,promise,repository-pattern,q

I have a feeling that the way I use promises is not correct Yes, you use the deferred antipattern a lot. Promises do chain, which means that you simply can return values and even promises from your then callback, and the .then() call will yield a promise for those...

Destroy angular $http success/error snippets after route change

angularjs,http,angular-ui-router,q

Solution here is: DO clean after ourselves. Best Practices ... Add teardown code to controllers and directives Controller and directives emit an event right before they are destroyed. This is where you are given the opportunity to tear down your plugins and listeners and pretty much perform garbage collection. Subscribe...

Q Reject promise within .then success callback

node.js,promise,q

This is actually covered in the q docs under the section Handling Errors. Instead of using the .then(success, fail) style, you'll want to chain your handlers to allow the success handler to throw to the fail handler. readLogFile() .then(function yay(data) { throw "Eek!"; }) .fail(function boo(e) { res.status(500).json({error: e}); });...

Promises in series

javascript,node.js,promise,q

You're not returning anything from the reduce function. accumulatedPremise.then(function (response) { should be: return accumulatedPremise.then(function (response) { ...

AngularJS how to use $q in Typescript

javascript,angularjs,typescript,q

There are several ways to return a promise... $http returns a promise with each of its ajax calls, $timeout also returns a promise. That being said you want to return a promise based upon something other than a scheduled event ($timeout, $interval) via $q you can do this... // assume...

Q.all is not working

javascript,node.js,protractor,q

* Updated * The simplified answer to your question is that the all() prototype method doesn't take parameters, so .all(doStuff) is only calling .all() on the promise returned by doSomething() and doStuff ends up being an argument that's never used. The simplest solution is to use nikc.org's solution. ...

KDB / Q Resetting random elements on newly created list (numerical vs symbol/char)

list,random,q,kdb,nul

To make it generic would be a matter of using the booleans to index rather than using them to multiply (as you currently are). However, for non numerical lists you'd need to reset values to nulls rather than to zero. These nulls would have to be the correct null corresponding...

How to pass parameters to Node's Q library's (denodeify) promise handler

javascript,node.js,promise,q

You can use .bind() like this: httprequestpromise.then(processhttprequest.bind(null, a, b, c)); This creates a dummy function that will add the arguments a, b, and c before calling processhttprequest(). Or, you can do it manually with your own stub function like this: function myfun() { var a, b, c; //do some work...

Mongoose.create + Q convert mongoose promises into Q promises

node.js,mongoose,promise,q

You don't pass the 'resolved' callback to the call to all, you call done on the returned promise and pass the callback to that: This worked fine when I tried it: Q.all([promise1, promise2]).done(function(docs){ console.log("promises resolved"); }); ...

How can I make a waterfall Q promises?

javascript,angularjs,promise,q,deferred

Create a function to handle the iterations: function go (urls) { if (urls[0]) { require(urls[0]).then(function () { go(urls.slice(1)); }); } } go(urls); ...

Why isn't my Q promise working?

node.js,q,node-mysql

Updated answer: You're probably losing the lexical scope to connection when you denodeify the query method. Looking at the Q documentation it says this can be an issue: If you are working with methods, instead of simple functions, you can easily run in to the usual problems where passing a...

Q.fail not working when using Q.allSettled

javascript,node.js,q

Yes, the promise returned by .allSettled() is fulfilled with an array of all of the results, whether they were fulfillments or rejections. If the returned promise somehow caused entry into both the .then() handler and the .fail() handler, then that would lead to some pretty confusing program flow and would...

What's a simple way to log a programming error in node?

node.js,q

Rewrite your final call like this: function errorHandler(err) { console.log('You had an error, ' + err); } first .then(second, errorHandler); The promise captures any exceptions that throw within it, you need to explicitly handle it. A variation that's q specific would be: first .then(second) .fail(errorHandler); You may consider this easier...

How to resolve compile error

typescript,q

According to the page which you linked to from DurandalJS it expects jQuery promises which you can swap with Q if you really want to. The jQuery deferred expects a function promise (see doc) while Q has a property called promise so in order for DurandalJS to work correctly it...

How do you return a value from one class method to another when using Q/promises/asynchronous functions?

javascript,node.js,asynchronous,q

I think you are looking for something like the following. Note that I have wrapped all the calls to deferred.resolve() into callbacks from asynchronous functions (in this case process.nextTick), since that would be a more realistic use case then resolving the promise before returning it, and is, I assume what...

Q promise with underscore .find()

javascript,find,underscore.js,promise,q

No, you cannot use _.find or any other synchronous iteration method with asynchronous callbacks - it doesn't work with filter either. You currently try to return from an asynchronous callback, which just won't work. You'll first need to write an asynchronous find function: function find(arr, predicate, i) { i =...

KDB+ / Q Table creation with dynamic number of columns

list,table,q,kdb

A table is a dictionary from a dictionary of symbol keys to a list of equal length vectors. Dynamically create the column names using "string til". q){ `id xkey update id:i from flip (`$"vals",/:string til y)!(y#x)?\:`8 }[3;4] id| vals0 vals1 vals2 vals3 --| ----------------------------------- 0 | lkamnmmm nfnbfmkm kiblpojl onhlghno...

Converting async code to q/promise code in nodejs

node.js,asynchronous,promise,q

So it seems like I needed to "promisify" my own functions before I could use them. Here's how I did it with Q: var Q = require('q'); anotherClass.prototype.duplicateUsername = function(username, callback) { return new Promise(function(resolve, reject) { var deferred = Q.defer(); if (usernameFound) { deferred.reject("error); } else { deferred.resolve("no err:...

Controlling the value of this in a promise

javascript,promise,q

the value of this is lost somewhere in the resolution of the deferred. The spec requires that promise callbacks are invoked without any this values. That's why resolve and reject don't even accept a parameter for it. If a callback wants to use some this, it needs to take...

How to use $limit and $sort with Q.nbind() in mongoDB

javascript,node.js,mongodb,mongoose,q

This is very simple just have a look at following code: var q = require('q'); var findSomeThing = q.nbind(SomeThing.find,SomeThing); SomeThing({"someId":"someIdValue"},{},{limit:2}).done(function(data){ //2 records will be retrieved here console.log(data); }); Hope this helps you!...

How do I tell if an object is a Promise?

javascript,promise,q,bluebird,es6-promise

How a promise library decides If it has a .then function - that's the only standard promise libraries use. The Promises/A+ specification has a notion called thenable which is basically "an object with a then method". Promises will and should assimilate anything with a then method. All of the promise...

How does Q.all work in NodeJS?

javascript,node.js,promise,q

Q.all cannot run before your forEach, since forEach is synchronous. But you actually push things in the array after Q.all has been called. Your way of using promises is a bit awkward : no need to use a deffered in a promise! Plus, you don't want to push the deffered...

Angularjs : mistake with $q

angularjs,q,deferred

Thank you all for your answers. Now it works ! Here is the VisiteService.js modified : var module = angular.module('app', []); module.service('visiteService', function($q, $rootScope) { this.getItems = function() { var deferred, result = []; deferred = $q.defer(); var db = window.openDatabase('database', '1.0', 'database', 200000); db.transaction(function(tx) { tx.executeSql("CREATE TABLE IF NOT...

Chaining timeouts results in last timeout rejected?

javascript,node.js,promise,q,bluebird

Currently you have 3 timeouts that all require that everything (your whole chain) finishes within 1s. I've got the feeling that you actually want to make 3 timeouts for each of the successive tasks: Promise.delay(2000) .then(function() { return Promise.delay(2000) .timeout(1000, 'Timeout 1'); }) .then(function() { return Promise.delay(500) .timeout(1000, 'Timeout 2');...

How does one use Q.all with chai-as-promised?

protractor,q,cucumberjs,chai-as-promised

Answering my own question: .should comes from the "should" assertions style - http://chaijs.com/guide/styles/#should. You need to run: chai.should(); after var Q = require('q'); but before Q.all([]).should.notify...: var Q = require('q'); var chai = require('chai'); var chaiAsPromised = require('chai-as-promised'); // *************** chai.should(); // *************** chai.use(chaiAsPromised); it("should all be well", function (done)...

Replacing callbacks with promises in Node.js

javascript,node.js,promise,q

With bluebird you can use Promise.promisifyAll (and Promise.promisify) to add Promise ready methods to any object. var Promise = require('bluebird'); // Somewhere around here, the following line is called Promise.promisifyAll(connection); exports.getUsersAsync = function () { return connection.connectAsync() .then(function () { return connection.queryAsync('SELECT * FROM Users') }); }; And use like...

What is the Bluebird equivalent of `Q.when`?

javascript,node.js,promise,q,bluebird

Is it Promise.resolve(someValue);? Yes....

Node.js Q promise forEach returning undefined

javascript,node.js,http,promise,q

As @sholanozie said, you aren't returning anything from parseRedditData. I'm guessing what you want is: var Feeds = function(){ this.reddit = new Reddit(); this.parseRedditData().then(function(data) { console.log(data); }); }; ... Feeds.prototype.parseRedditData = function(){ var _this = this; return this.getData(this.reddit.endpoint).then(function(data){ return _this.reddit.parseData(data); }); } ...

Q promises and mongo db q.all

node.js,mongodb,q

I think you were just confused about when the entire process was finished. You need to wait until the entire recursive promise chain has resolved. I think you could use the original code with a slight change to where processPlaylist() is called: var PlaylistCollection = require('./models/playlist'); var AssetCollection = require('./models/asset');...

Accessing the promise object from within the then function

node.js,asynchronous,scope,promise,q

This is what I have: promises[i].then(function(data) { console.log("In function ", this.query); processSearchResults(data,this.query); }); The code prints "In function undefined". The spec mandates that the callback is called with nothing for the this value, so this will refer to the global (window) object in sloppy mode, which does not have...

node.js redis and how to use promise when using a module

javascript,node.js,redis,promise,q

like @brad said, you could use Q.all, it would take an array of promises as input and then return an array of results when all the promises are finished: there is a mistake in your answer: Redis.prototype.exists = function (key) { return this.client.exists(key) // CHANGED, you still need to return...

Nested $http calls $q.all returns promises but not resolved

javascript,angularjs,promise,q

$q.all takes an array of promise. Here, you are doing $q.all([myPromises]), which resolve instantly, because '[myPromise]' is an array and not a promise (you give an array parameter with first and only element is an array of promise when you should simply use the promise array. So [] and not...

AngularJS $q.all update/notify not called why?

angularjs,q,angular-promise

$q.all creates a new singular promise that once all the previous promises are complete will then continue on. If you want to do each one individually you'll have to reference them individually.

How do I use promises in node.js to clean up a chain of callbacks?

javascript,node.js,callback,promise,q

I had similar issues and I realized later it was because of Q. In my opinion Q has a messy API and it's cumbersome to use with very few simple examples. I recommend trying any other library, though I do recommend Bluebird. With Bluebird you could do the following: var...

Using Angular how can we make a call after completing bunch of asynchronous calls

angularjs,q

The problem is success() does return the original promise. then() call returns a promise (resolved with a value returned from a callback) while .success() is more traditional way of registering callbacks and doesn't return a promise. So a proper solution is $q.all([ myFactory.getPoints().then(function (response) { $scope.points = response.data; return response.data;...

Node.js Q promises then() chaining not waiting

javascript,node.js,promise,q

The problem is you don't pass functions, but the result of function calls. Instead of createUser(user_data) .then(createClient(client_data)) you should have createUser(user_data) .then(function(user){ createClient(client_data) // no need for the user ? really ? }) ...

NodeJS Q and module

javascript,node.js,q

Your layertoken.js returns a Promise LayerToken. To get the actual value you call .then on it LayerSessionToken = layerToken.generateToken(); LayerSessionToken.then(function(actualValue){ // do something with actualValue }); More info on how Promises work...

How to avoid nesting promises with $q

javascript,q,angular-promise

caveat - I am more familiar with the Promises implementation in the "promise" npm module, but if q works the same way, you can do this: var findRepositoryPromise; findRepositoryPromise = RepositoryService.find($stateParams.host, $stateParams.owner, $stateParams.repository); findRepositoryPromise.then(function(response) { $scope.selectedRepository = response.repository; return TeamService.getUserTeams($rootScope.user.id); }).then(function(response) { $scope.teams = response.teams; $scope.selectedTeam = $scope.teams[0]; $scope.selectedTeamId =...

NodeJS sequential async with conditional statements

javascript,node.js,asynchronous,promise,q

Assuming step2 and step3 are functions returning a promise what is the problem with: step1.then(function() {   if( opt ) { return step2(); } else { return step3(); } }) .then(step4); EDIT Your first example step1.then(opt && step2).then(step3); would look like this: step1.then(function() {   if( opt ) { return...

Q.nfcall or Q.denodeify for constructors

javascript,promise,q

Constructors shouldn't make asynchronous calls. This is not fun to do because the person making this library are performing async IO in constructors which is totally not cool of them :) I suggest you wrap that function in a callback: function fooBar(val, cb){ new FooBar(val, cb); } Which would let...

How to pass a hashed password in a promise before posting it to the database using a Node.js server?

javascript,node.js,promise,q,bcrypt

You could simply move your database queries, to inside the callback of the hash, so that when the hash call back is ready it would then save it. var bcrypt = require('bcrypt'); app.post('/api/users', function(req, res) { bcrypt.genSalt(10, function(err, salt) { bcrypt.hash(req.body.password, salt, function(err, hash) { var newUser = new User({...

Implementing Q with Strongloop Loopback

javascript,node.js,promise,q,loopbackjs

Support for promises are coming into core see: https://github.com/strongloop/loopback/issues/418

KDB+ / Q unique random values with variable for amount

random,q,kdb

This will give you num unique numbers between 0 and 9. q)(neg num)?10 ...

Accomodating a Q.all in a promise chain

javascript,node.js,promise,q

Q.all takes an array of promises, but then returns a promise (that is the only resolved when every promise in the array is resolved. So, I think you need to return the result of Q.all in order to not immediately call the next then: Q('begin') .then(console.log) .then(function() { return Q.all([100,200,300,400].map(f));...

Javascript Kriskowal Q JS promise not working

javascript,jasmine,q

Your it is finishing immediately, instead of after the promise's resolution/rejection. it("should return the promise", function (done) { test.testt().then( function (a) { console.log(a); done(); }, function (b) { console.error(b); done(); } ); }); See here for more info....

Why is the promise still pending?

javascript,q

Because output is not new Foo(bar).go(). It is assigned the result of the .finally() call, and will not be resolved untill the finally callback is done. This will work as expected: var output = new Foo(bar).go(); output.finally(function() { console.log('output.isPending?:', output.isPending()); console.log('output.isRejected?:', output.isRejected()); console.log('output.isFulfilled?:', output.isFulfilled()); }); ...

Using Q.js promise for unit-tests: timeout of 2000ms exceeded

javascript,unit-testing,asynchronous,mocha,q

It looks like you have your error handler as part of the the same then with your test case. This means you won't catch any errors thrown by the expect. Try this and see if you get a different error: it("Api test", (done) => { return api.post({}) .then(value => {...

What is the purpose of “done” in q promise chains?

javascript,q

As a doc comment in the source says: Terminates a chain of promises, forcing rejections to be thrown as exceptions. https://github.com/kriskowal/q/blob/v1/q.js#L1768...

Notify promise angular remove callback

javascript,angularjs,q,angular-promise

You can use $on, $broadcast and $emit to achieve a similar behavior. Just $broadcast(name, args); an event and register a listener $on(name, listener);. So when you got your data you just broadcast to everybody that you've got it. $broadcast('gotTheData', actualDataObject); Then in your controllers $on('gotTheData', function(event, actualDataObject) { ... update...

Prevent multiple ajax requests onclick

javascript,ajax,angularjs,q

You can put a lock on the function to prevent the code from running multiple times at once or at all: // your service $scope.isRunning = false; var getItems = function () { if(!$scope.isRunning){ $scope.isRunning = true; var def = $q.defer(); Items.get().then(function (items) { def.resolve(items); }, function (err) { ......

How to to nest a sequence with Q?

javascript,promise,q

I'm really not sure how your code is producing any output at all. You're trying to use a promises as though they were deferreds, and you're using document.write(), which I would imagine is overwriting your whole page. And while not necessarily a bug, you are using the deferred antipattern. So...