FAQ Database Discussion Community


passing callback or promise to the different module , which one is better and efficient?

callback,promise,loopbackjs
In my application, I am passing callback to different module and so on. Same thing I am able to achieve using bluebird promise. According to best code practice, which one is better?...

How to handle request-promise errors properly?

javascript,node.js,promise
So I'm using request-promise in a script that I have that loops through a list of urls and fires of requests. Then I want to do something w/ the data received once all the requests are complete. I have the following: var rp = require('request-promise'); rp.get({ uri: 'http://httpstat.us/500', transform: function(body,...

How to return from a promise if Ajax is not required?

javascript,jquery,ajax,promise
I am using jQuery promises to pre-fill the value of a select option. This works fine, but my question is about what to do when an Ajax call is not actually required, so the code does not return a promise. The code below works fine if this.orgId is not undefined....

Why can I not chain .catch when calling mongoose Model.create in node

node.js,mongodb,mongoose,promise
I have a mongoose schema and am calling Model.create(). When I chain 'catch' after the 'then' I get undefined is not a function, if I just call the error function as the second parameter to the 'then', then I don't. But when I call methods such as Model.find, I can...

Resolve a promise once all internal concurrent promises have resolved or rejected

javascript,promise,es6-promise
I am looking for something similar to Promise.all that will continue to resolve promises concurrently even in the event that one or more of the promises reject or throw an error. Each request does not rely on another request. Close to what I want - please see comments function fetchRequest...

Rxjs Promise like Observable

promise,rxjs
I'd like to find a receipt for provide a Promiselike Observable i mean: that Observable provides a single value and completes, and any subscriber (before and after completion) should get that single value. i came out with a combination of Rx.Observable.create publishLast and connect. var getPromiseLike=function(){ console.log('getPromiseLike()'); //// var an_object={};...

How to use promises to do series without duplicate code

node.js,promise,bluebird
I need execute a code in series, I need execute the same function N times Example // execute asynFunc 4 times in series object.asynFunc() .then(function() { return object.asynFunc(); }) .then(function() { return object.asynFunc(); }) .then(function() { return object.asynFunc(); }) I want execute the same function 100 times...

Chaining Asynchronous Functions Node.js bluebird mongoskin

javascript,node.js,asynchronous,promise,bluebird
I have been reading many posts on how to chain asynchronous functions but I just can't seem to get it right! As the title indicates. I am trying to chain mongoskin database calls together, so that i can gather all the information in chunks and then finally send the accumulated...

jQuery .then() call two functions

javascript,jquery,promise
If I have three functions a, b, and c: function a() { var deferred = new $.Deferred(); // stuff -- resolve deferred once async method is complete return deferred.promise(); } a().then(b) This works fine, but how could I also call function c after a is finished? Something like: a().then(b,c)...

underscore _.each and promise

underscore.js,promise
This is probably a classical problem but I'm having an hard time to find a proper answer. var total_debit = {}; _.each(somearray, function(x) { if(!total_credit[b.currency]) { total_credit[b.currency] = 0; } // total_debit["usd"] HAS BEEN INITIALIZED! total_debit["usd"] += x }); _.each(total_debit, function(td) { // do some stuff }); The problem is...

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

javascript,node.js,redis,promise,q
I have an Express route like this in an node server (file is required): var redis = require('../modules/redis'); module.exports = function (app) { var redisClient = redis.init(); app.post('/auth/ticket', cors(), function (req, res) { var hashes = ['hash1','hash2', 'hash3']; var candidates = []; // An array to collect valid hashes var...

Protractor - Wait for async promise before doing next

selenium-webdriver,webdriver,promise,protractor,angularjs-e2e
First of all, I've already checked various post and blogs concerning that point and I still can't figure out how to make it correctly. I have tried many different combinaison of : browser wait protractor.controlFlow().execute protractor.controlFlow().await( ...Still no success.. My problem Within my beforeEach function, I'd like to call a...

How to run lastTask after forEach

javascript,angularjs,cordova,ionic-framework,promise
I have an array of images which I iterate and upload each to a remote server. Once the file is uploaded I use the result to get the file name and push to another array. The problem I'm having is that not all results are being pushed to the array....

Acces to jQuery $.get URL from Bluebird Promise object

javascript,jquery,promise,bluebird
I use Bluebird promises with jQuery $.get() like so: var p = Promise.resolve($.get(url.address, url.options, 'json')).then(function (result) {... and handle them with: p.timeout(100).catch(Promise.TimeoutError, function (error) { console.log(p); // here I want to log in that Promise took too long to execute and access what user actually asked for }); How to...

Angular chaining AJAX calls

javascript,ajax,angularjs,promise
I have to do 2 AJAX calls. Second one depends on the first call result. Right now I do it like this: Service.getA(car).then(function(carInfo) { if (carInfo.success) { Service.getB(carInfo.number).then(function(holderInfo) { console.log(holderInfo); }); } }); Service: getA: function(car) { return Server.execute({ method: 'GET', url: 'a/a', params: { car: car }, }).then(function (carInfo)...

Why my recursive Javascript function with Promises fails

javascript,recursion,promise
I have JSON object that I need to clean up of properties starting with $. So given structure below it should get rid of $aaa, $bbb, $ccc and $eee: { $aaa: "$aaa", bbb: "bbb", $ccc: { $ccc2: "$ccc2", ccc2a: "ccc2a" }, ddd: { $ddd: "$ddd2", ddd2a: "ddd2a" }, $eee: "$eee",...

Ember Controller Property, Promise, and Scope

javascript,ember.js,promise
Very new to Javascript and even newer to Ember here, I have an async hasMany association and I'm trying to sum a property on the child model (tournament) in the parent models controller. My understanding of function scope is that the inner functions will have access to everything in the...

Can Bluebird Promise work with redis in node.js?

javascript,node.js,redis,promise,bluebird
Here's my original code to fetch a user php session which is stored in redis: var session_obj; var key = socket.request.headers.cookie.session session.get('PHPREDIS_SESSION:'+key,function(err,data){ if( err ) { return console.error(err); } if ( !data === false) { session_obj = PHPUnserialize.unserializeSession(data); } /* ... other functions ... */ }) I would like to...

Bluebird PromisifyAll without any Async suffix, i.e. replace the original functions possible?

javascript,node.js,promise,bluebird
Bluebird has a promisifyAll function that "Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain." It creates functions with a suffix Async. Is it possible to replace the old functions entirely? The replaced functions...

Nested promises in ui-router resolve

angularjs,nested,angular-ui-router,promise,resolve
I have been struggling for a while with the following problem: I would like to get some data before the view shows, (resolve). But some of the data is dependend on the result of another promise. It goes like this: I get the job id (index) from the $stateParams and...

ui-router: async data in templateUrl function

javascript,angularjs,angular-ui-router,promise,angular-promise
I've run into quite a novel problem with ui router. I'm basically trying to query my API for a template url, which is stored and returned as a Resource object. The problem, is it seems that the templateUrl function is returning as undefined. My code is as follows: (function() {...

return an error from $http.success

angularjs,callback,promise
I am working in Angular and I need to signify an error to a promise further down the chain when the result is being resolved in .success(). I call a function in my service from my controller like myService.myFunction().then( function(results){ // do success stuff }, function(err){ // do failure stuff...

Promise fulfillment handler undefined

javascript,node.js,promise,bluebird
Very basic, it seems, implementation of a Promise based implementation is not returning the value/data I expect to see. This is how I am expecting this interface to work: sdk.request(options) => Promise~Response → Object (JSON) Here is the code in my model: return sdk.request(options).then(function (value) { return value; }); When...

use angular factory to hold a value for rest of application to access to minimize server calls

javascript,angularjs,promise,factory,angular-promise
I have the following factory: angularModule .factory('ArticleCategoryService', function ($http, $q) { // Service logic // ... var categories = []; var _getCategories = $http.get('/api/articles/category').success(function (_categories) { categories = _categories; }); // .error( function (data, status, headers, config) { // }); // Public API here return { getCategories: function () {...

Implementing a fallback using promises

javascript,jquery,promise,jquery-deferred
it is a common pattern that we cascade across a list of sources of data with the first success breaking the chain like this: var data = getData1(); if (!data) data = getData2(); if (!data) data = getData3(); et cetera. if the getDataN() functions are asynchronous, however, it leads us...

Selenium WebdriverJS Promise Loop

javascript,selenium,promise,webdriverjs
I'm trying to look for the "More" link in a container to keep clicking on it until the link is no longer there. I'm creating a deferred and returning it with the fulfill call happening once there is no longer a "More" link available. .then(function (previousResults) { var deferred =...

Javascript: Solving the asynchronous loop to push an array in Parse.com

javascript,arrays,callback,promise
I'd like to get the final result from a loop where I'm pushing objects into an array. I know from the console.log that all of the results go into the array but I can't get my desired array out of the double loop to use for anything. I understand that...

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

javascript,node.js,coding-style,promise,q
I have some code like this: function example(data){ asyncFnOne() .all([asyncFnTwo(), data]) .spread(asyncFnThree) .done(); }; It doesn't matter what those functions do. The problem I have is that I don't know how asyncFnThree can access both data from asyncFnTwo and from the function parameters. The way I solved the problem is...

Execute native js promise in series

javascript,node.js,promise
I have to call a promise for some async task for each item in an array but I would like to execute these serially. Promise.all is useful only to have a new promise that merges a list of promise but it does not invoke them in a sequence. How can...

How to construct a promise chain involving multiple dependence? [duplicate]

javascript,promise
This question already has an answer here: How do I access previous promise results in a .then() chain? 6 answers I want to construct a promise chain as below. The arrows represent dependence: B needs the output of A; C needs the outputs of both A and B. Since...

Recursive thenables? [duplicate]

javascript,performance,recursion,promise
This question already has an answer here: Building a promise chain recursively in javascript - memory considerations 2 answers I'm trying to achieve a pattern in which I invoke an endless recursive loop of thenables (Promise-based chaining) that are likely to run for several hours (I'm playing around with...

How to prevent false positives with mocha, promises, and catch blocks

javascript,promise,mocha
I want to take advantage of Mocha's built in promise support, but i'm having difficulty dealing with false positives when I want to test catch branches in my promise chains. This question gets closest to what I want, but the solution requires every developer on my project to add a...

nesting promises to encapsulate common flows

javascript,promise
I'm quite new to promises in javascript and I'm still trying to work out the best way to chain promises together in javascript, e.g. something().then(function(result){ console.log(result); }) function something(){ return another().then(function(result){ return "message"; }) } if something() and another() both return promises, will the another() and its then() be called...

promise – can't find variable process

javascript,promise,react-native,es6-promise
for my (first) react-native project I use the Node module react-native-refreshable-listview requiring a CommonJS/A+ promise method to display an indicator. However, everytime the promise's then method is invoked by the consumer (for example this.doSomething().then(function() { ... })) I get the following error: Error: Can't find variable: process stack: requestFlush index.ios.bundle:43767...

Parse.Cloud.job promise not working

javascript,parse.com,promise,cloud-code
What I am trying to do here are: Remove all contents in a class first, because every day the events.json file will be updated. I have my first question here: is there a better way to remove all contents from a database class on Parse? Then I will send a...

Promise doesn't resolve the right value [duplicate]

javascript,promise,es6-promise
This question already has an answer here: Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference 3 answers function retRGObj(objName, xTime) { return new Promise( function (resolve, reject) { let data = {} findR(objName, xTime).then(function (msg) { data.R = msg console.log(data)...

How to break when found the item?

javascript,angularjs,promise,each,web-testing
I have a web test code and I don't want to iterate over the rest after i found the item. This code iterate to all item and the finally return. How to resolve this problem, because in the each I don't break! isItemPresent: function (name) { var def = Q.defer();...

How to make multiple mysql queries in Node with promises

mysql,node.js,promise
G'day all, I'm trying to convert some old php code over to Node, and part of the journey has been trying to figure out the best way to perform sql queries against my database (I'm using SQL so I can port the existing database over). I've got them working, but...

chaining recursive promise with bluebird

javascript,recursion,promise,bluebird
I have a promise chain with a recursive promise doAsyncRecursive() in the middle like so: doAsync().then(function() { return doAsyncRecursive(); }).then(function() { return doSomethingElseAsync(); }).then(function(result) { console.log(result); }).catch(errorHandler); doAsyncRecursive() has to do something and if it at first does not succeed, i then after want to try every 5 seconds until...

errors not being thrown after promise

javascript,exception,promise
i have a weird situation i would like to know how to solve. in my app errors that happen after functions with promises do net get thrown and the app just stalls. here an example: getTenant = (req) -> deferred = Q.defer() deferred.resolve('foo') if req.info.referrer deferred.resolve('bar') if !req.info.referrer deferred.promise Routes...

Why does deferred.when() return promises in done callback?

javascript,jquery,ajax,promise
Why is jQuery's deferred.when returning promises in the done callback, rather than their corresponding response data? var data = { json: JSON.stringify({ text: 'some text', array: [1, 2, 'three'], object: { par1: 'another text', par2: [3, 2, 'one'], par3: {} } }), delay: 3 }; var firstRequest = $.ajax({ url:'/echo/json/',...

AngularJS how do I execute code only after a promise is resolved? (with Restangular)

angularjs,promise,restangular
This might be a nooby question but I still haven't been able to get my head around promises and specifically how to write code with them. (I've read several articles but most of them are abstract and I simply haven't written enough to have a clear picture) I've got an...

Nodejs Promise.all() resolving always

javascript,node.js,promise,es6-promise
I am new to promises. I am trying to ping some machines to check whether they are active. I am using native NodeJS promises. My ping function : function ping(addr) { return new Promise(function(resolve, reject) { var args = ['-n', '1', '-w', '5000']; args.push(addr); var ls = cp.spawn('ping.exe', args); ls.on('error',...

How do I convert this code using promises?

node.js,callback,promise
I am new to Nodejs.I want to convert this code to promises (nodejs).This includes four callback function get(),abc1(),pqr(),xyz(). It gives error of "cannot read property 'then' of undefined" Can anyone fix it? I am trying it to convert into promises from this example here var jwt = require('jwt-simple'); var mysql...

Flattening a Promise map

promise,bluebird
I'm curious how you go about flattening the results from a Promise map of promises that are arrays. I have a function that Promise.maps over a set of values that they themselves are promises (needing to be resolved) and are returning an array. So, I get back something like: [...

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

javascript,node.js,callback,promise,q
I've node app with function that inside call to to other two function,I want to use some async behavior for it,what is recommended to use in this case. example will be very helpful. function myFunction(req,res){ //from here this is the first place which I want to use warp in function...

Why is AngularJS error message empty on error handling?

javascript,angularjs,error-handling,promise
I am using the AngularJS code to make a request to the server. On success it works fine, but when I redirect the request to some other domain provoking the CORS problem intentionally, error handling function is invoked but errorData is empty. In Chrome when i debug I can see...

When Promisifying a XMLHttpRequest, how to catch a throw Error

javascript,xmlhttprequest,promise
After I've Promisified my XMLHttpRequest, like so: var Request = (function() { var get = function(url){ return request('GET', url); }, post = function(url){ return request('POST', url); }, request = function(method, url) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open(method, url); xhr.onload = function(e){ if (xhr.status...

Class declaration cannot close over value 'fulfill' defined in outer scope - Swift 2.0

xcode,swift,closures,promise
I'm trying to convert my app from Swift 1.2 to Swift 2.0 and I'm encountering the following error: class B { func test() -> Promise<A> { return Promise<A> { (fulfill, reject) -> Void in anotherPromise.then { _ -> Void in return fulfill(A()) // Class declaration cannot close over value 'fulfill'...

Can I catch an error from async without using await?

javascript,promise,ecmascript-async-await,es7
Can errors from a non-awaited async call be caught, sent to an original encapsulating try/catch, or raise an uncaught exception? Here's an example of what I mean: async function fn1() { console.log('executing fn1'); } async function fn2() { console.log('executing fn2'); throw new Error('from fn2'); } async function test() { try...

how to pass result of $.get to return of another function

javascript,jquery,ajax,promise
I have trouble with the callback of jquery $.get() ajax function. I'm using the DataTables plugin and trying the "expanding row to see children details" example (can be seen here https://www.datatables.net/examples/api/row_details.html). The problem is this line: row.child( format(row.data()) ).show(); the function format() renders html direct rom the front end as...

Dynamic Chaining in Javascript Promises

javascript,promise
How can I perform dynamic chaining in Javascript Promises, all the time I have seen only hardcoding of the calls for eg., (promise).then(request/functionName).then(request/functionName)

Working with promises jQuery

javascript,jquery,arrays,promise,filereader
I have to store some images, I'm taking the value like this: var imgGaleria1 = $("#imgGaleria1")[0].files[0]; var imgGaleria1Blob; if (imgGaleria1) { var reader = new FileReader(); reader.onload = function (e) { reader.readAsDataURL(imgGaleria1); imgGaleria1Blob = e.target.result; }; } But obviously I can't store into imgGaleria1Blob, because reader is just async task,...

chain array of promises with bluebird

javascript,arrays,promise,bluebird,es6-promise
I'm a working my way with promises and I'm stuck with my use case. I have an array of transformer functions (each function is a promise and modifies some JSON structure). Let me show some code. Lets say this is my JSON structure (array) var data = [{a: 1, b:2},...

Node.js Q promises then() chaining not waiting

javascript,node.js,promise,q
I am trying to refactor the following code to avoid the callback hell, transforming it into: createUser(user_data) .then(createClient(client_data)) .then(createClientPartner(clientpartner_data)) .then(function(data) { cb(null, _.pick(data,['id','username'])); }, function(error) { cb(error); }); As you see, I created a method for each one of the steps: function createUser(user_data) { console.log('createUser'); var deferred = Q.defer() new...

Resolve promise in service without callback in controller

angularjs,callback,controller,promise,angular-promise
I would like to ask/discuss wether this is good or bad practise - what are the pros and cons of making a service call insde a controller as clean and short as possible. In other words: not having a callback anymore but make use of the Angular binding principles of...

Log all reject promises in Q

node.js,promise,q
Is there a way to configure Q to log or call a specific function on all rejected promises (like an interceptor)? Many exceptions are being swallowed in my application, and put error handling in all my promises just for logging purposes would be duplicated work to do. Thanks!...

Promises for going through URLS

javascript,web-scraping,promise
I'm trying to figure out a way to process through a dynamic number of URLS. The idea is to have a while run until we reach the limit of whatever we are searching for - let's say URLS for example. return new Promise(function(resolve, reject) { var links = []; var...

What does Protractor browser.wait return if the condition never becomes true?

promise,protractor,wait
I want to use the browser.wait function to repeatedly check if a button element is present for a certain amount of time then use the relevant callback. Below I have the code that doesn't use the wait. detailsButton.isPresent() .then(function(present){ if(!present) { callback(); } else { callback(new Error('The details button was...

delay for jquery promises

jquery,promise,jquery-deferred
I cannot find delay or wait function for jQuery promises. I have found one function on the SO (Using jQuery.Deferred to avoid nested setTimeout callbacks): function delay(time) { return function () { console.log("Delaying"); var ret = new $.Deferred(); setTimeout(function () { ret.resolve(); }, time); return ret; }; } And, it's...

Plain JavaScript + bluebird promises asynchronous for/while loop WITHOUT USING NODE.JS

javascript,for-loop,while-loop,promise,bluebird
There seem to be many answers to questions on how to use bluebird promises to call asynchronous functions from a for / while loop, but as far as I can see, all require node.js to work (e.g. promise.method() or process.nextTick() ; e.g. such as: While loop using bluebird promises )....

Passing “this” inside a promise?

javascript,jquery,ajax,promise
I am trying to learn about promises. My URL will contain three ID parameters, e.g. #org=123&num=145&denom=467 and I want to use these to select the values of three select elements on my page (each one with an Ajax source), e.g. <select id="org"><option selected val="123">Birmingham University</option></select> <select id="num"><option selected val="145">Maths</option></select> <select...

How to call a function repeatedly after it finishes?

javascript,node.js,promise
I want to call a function main() which contains a lot of asynchronous db-connection calls. I want to call this function repeatedly after an iteration of main() gets finished. How should I do that in Nodejs? I think there is some way to use promises over here to do this....

Saving data using promises

javascript,parse.com,promise
On Parse.com I have the following function, and my question follows: function myFunction(array, value) { var logMessage; logMessage = "array: " + array.length.toString(); console.log(logMessage); if (!array.length) return; if (!value) value = Math.min(10, array.length); if (array[array.length - 1].get("advertisePointNumber") >= value) return; var classPromise; array[array.length - 1].set("advertisePointNumber", value); logMessage = "(BIS)array: "...

Preserving arguments when returning data from deferred.then()

javascript,jquery,promise
How can I pass more than 1 argument when returning data in a deferred.then callback? var data = { json: JSON.stringify({ text: 'some text', array: [1, 2, 'three'], object: { par1: 'another text', par2: [3, 2, 'one'], par3: {} } }), delay: 3 }; $.ajax({ url:'/echo/json/', data: data, type: 'POST'...

Why does my hash of promises resolve before passed promises resolve?

javascript,asynchronous,promise,rsvp.js
I have been using promises for a while, but now and then I stumble into problems that I cannot seem to resolve (no pun intended). I have an array of files for which I have to perform asynchronous functions call for each file to fetch some metadata. I'm using RSVP.hash()...

Retrieve HTTP status from Promise on Play 2.3.7

java,json,playframework,promise,playframework-2.3
in our project we use JSON for data transmission between front and backend. Basically we creating requests by preparing WSRequestHolder, just like the play doc tells to (https://www.playframework.com/documentation/2.3.7/JavaWS) and then posting a json string. The WSResponse is then mapped "asJson" returned as a Promise. But unlike WSResponse, the JsonNode does...

Object # has no method 'catch'

node.js,mongoose,promise,bluebird
My user lib have following code for register function register { // do some validation on lib level //user is instance of user collection user.save() .then(function(error,records, numberOfRecords) { // got any kind of error if (error) { next('fail',msg,{error_code : 510, exception : ex} ) return ; } next('success','good', records );...

Issue with Angular Js resolve method

angularjs,angular-ui-router,promise,angular-ui,angular-promise
Hi I have a $stateProvider like below. $stateProvider .state('team.details', { url: '/:teamId', views: { '@': { controller: 'teamDetailsCtrl', templateUrl: 'src/modules/team/details/teamDetails.html', resolve: { user: function ($stateParams, TeamResource) { return TeamResource.get({ teamid: $stateParams.teamId }).$promise; } The TeamResource.get is calling a rest api and everything is working fine if the data is sent...

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

javascript,node.js,promise,q,bluebird
Switching over to Bluebird from Q, I just want to make sure it's culturally correct: Is there an equivalent to Q.when(someValue); or Q(someValue);? Is it Promise.resolve(someValue);?...

Do I always need catch() at the end even if i use a reject callback in ALL then-ables?

javascript,promise,es6-promise,rsvp-promise
I am putting catches at the end, but they are returning empty object in one particular instance at least. Is a catch necessary for anything unbeknownst, or is it just screwing me up? $( document).ready(function(){ app.callAPI()//a chainable a RSVP wrapper around a jquery call, with its own success() fail() passing...

How do you push 10,000 results into an array before moving on in Parse.com

javascript,arrays,parse.com,promise
I have a Parse.com query and a function where I want to send the data from the Parse.com query. I need to sum all of the results from the table and it returns more than 1,000 Parse.com objects. I'm sure there are many ways to deal with this issue but...

Access $scope from Factory method called from template ng-click

angularjs,promise
I have my Jade file: button(ng-click='item.accept(item)') And then the accept method in my Factory: accept = function(item) { return Item.update(item); }; However, I'm trying to provide some sort of visual feedback to the user that item has been saved/updated on the server. How can I access the $scope object from...

How can I promisify a simple asynchronous function I wrote? [closed]

javascript,node.js,asynchronous,promise
Setup While writing some numerical Javascript code for Node, the thought occurred, "Why not make this asynchronous?" E.g., var mySquare = function(x, callback) { callback(null, x * x); } mySquare(3, function(err, res) { console.log(res); }); // prints 9 except with a much more complex calculation, and one that might throw...

Running promises in small concurrent batches (no more than X at a time)

javascript,node.js,asynchronous,promise,bluebird
The Async library has functions like eachLimit which can be used to efficiently spread a big batch of jobs over multiple CPU cores, like this: var numCPUs = require('os').cpus().length; var exec = require('child_process').exec; async.eachLimit(someArray, numCPUs, function (value, done) { exec('something --input' + value, done); }, finalCallback); This avoids overloading the...

Differences between Deferred.then(null,func) and Deferred.fail(func) in JQuery?

javascript,jquery,promise
I found out today that Deferred.then(null,func) and Deferred.fail(func) aren't the same thing in JQuery. In ES6's promise, Promise.then(null,func) and Promise.catch(func) are the same thing, so I was confused by JQuery's functions. The only difference I know of is this: $.Deferred().reject().promise() .fail(function(){ return $.Deferred().resolve().promise(); }) .then(function(){ console.log('fail caught error'); // NOT...

How can I synchronously determine a JavaScript Promise's state?

javascript,promise,es6-promise
I have a pure JavaScript Promise (built-in implementation or poly-fill): var promise = new Promise(function (resolve, reject) { /* ... */ }); From the specification, a Promise can be one of: 'settled' and 'resolved' 'settled' and 'rejected' 'pending' I have a use case where I wish to interrogate the Promise...

how to correctly use promises to return 2 different results [duplicate]

javascript,promise,ecmascript-6,es6-promise
This question already has an answer here: How do I access previous promise results in a .then() chain? 6 answers I am trying to use Promises in JavaScript using ES6 to return data from 2 methods from an object, which would in production call out to an endpoint. My...

How do I stop error propagation in JQuery's $.Deferred()?

javascript,jquery,promise
I thought fail() would stop error propagation, but that doesn't seem to happen. Here's what I have: someAsynTask() .then(function(){ 1/0; }) .fail(function(){ console.log('Error handled.'); }) .then(function(){ console.log('test'); // not printed (expected it to print) }) .fail(function(){ console.log('More errors?'); // printed (nor expecting it to print) }); How do I make...

Waiting for promises - code hangs

javascript,node.js,promise
I am using Javascript Promises for the first time and ran into something I don't understand. What I am trying to do is create a validation phase which runs around and checks things - eventually waiting for all promises to resolve. To do this, I create a validation promise: validate...

How can you retry after an exception in Javascript when using promises?

javascript,node.js,exception-handling,promise,bluebird
I'm using the Bluebird promise library. I have a chain of promisified functions like the following: receiveMessageAsync(params) .then(function(data)) { return [data, handleMessageAsync(request)]; }) .spread(function(data, response) { return [response, deleteMessageAsync(request)]; }) .spread(function(response, data) { return sendResponseAsync(response); }) .then(function(data) { return waitForMessage(data); }) .catch (function(err) { // handle error here }); Occasionally...

How can I use `Q.set`?

javascript,promise,q
According to the API reference Q provides promise extensions for working with objects, but they don't behave as I would expect. Consider the following line of code: Q({foo:"bar"}).set("foo","baz").then(console.log); I would have expected {"foo": "baz"} to be printed, but it's actually undefined. Do I misuderstand the set method, or am I...

React Native: Chain Async Calls. e.g to AsyncStorage?

javascript,promise,react-native
I'm trying to chain several calls to AsyncStorage.getItem() but cannot seem to get the calls to trigger in the correct order. I seem to manage to drop out of the loop with the last item completed before earlier items. It appears that React uses a different syntax for promises than...

Using PromiseKit to force sequential download

ios,objective-c,promise,promisekit
I am using PromiseKit and would like to force sequential download of JSONs. The count of JSONs might change. I have read this about chaining. If I had a fixed number of say 3 downloads, this would be fine. But what if I had a changing count of download that...

Using Promise.all() for multiple http/oauth queries

javascript,oauth,promise
I'm trying to wait for the output of two OAuth calls to an API, and I'm having trouble retrieving the data from those calls. If I use Promise.all(call1,call2).then() I am getting information about the request object. First, here's the setup for the fitbit_oauth object: var fitbit_oauth = new OAuth.OAuth( 'https://api.fitbit.com/oauth/request_token',...

AngularJS: Unable to pass a factory's $http.get result to the controller (via $routeProvider)

angularjs,angular-ui-router,promise
I have a CRUD operation I would like to reuse, so I have a factory that gets passed to the controller via the $routeProvider/resolve. But I see that the controller resolves before the factory's GET request comes back. How can I set up promises so that $routeProvider doesn't pass undefined...

Fetch polyfill, undefined PromiseValue

javascript,reactjs,promise,es6-promise
Trying to make a DELETE request using fetch polyfill, but I get Uncaught TypeError: Cannot read property 'then' of undefined, this is the error on promise.then() here is how I do it: function deleteData(item, url) { fetch(url + '/' + item, { method: 'delete' }).then(response => { return response.json(); });...

Is Node.js native Promise.all processing in parallel or sequentially?

javascript,node.js,promise,es6-promise
I would like to clarify this point, as the documentation is not too clear about it; Q1: Is Promise.all(iterable) processing all promises sequentially or in parallel? Or, more specifically, is it the equivalent of running chained promises like p1.then(p2).then(p3).then(p4).then(p5).... or is it some other kind of algorithm where all p1,...

Waiting for Nested Promises to complete

ember.js,coffeescript,promise
I have a complicated object graph I'm building up in an Ember Controller. export default Container({ username: DS.attr('string'), items: DS.hasMany('item') }) export default SomeDetail({ foo: DS.attr('string') }) export default Item({ detail_type: DS.attr('string'), detail_id: DS.attr('number'), container: DS.belongsTo('container') }) So, to set all this up, I'm basically trying to Create the conatainer,...

Sequential Loading Using Promises

javascript,promise,ecmascript-6,bluebird,es6-promise
I've got an array of asynchronous calls that I want to be called sequentially, meaning that I don't want to call the second promise until the first is complete, and so on. In the following example, I've got a loop that creates unique images on the fly and appends them...

Are bluebird promises blocking in nature

javascript,node.js,promise,bluebird
I may be a bit new to understand the underlying functioning of promises esp bluebird. What i am trying to accomplish is an API server that processes bulk write of 250K+ rows into a database. It takes around 30s to complete the request. I want the API server to return...

wrap code by promises

javascript,jquery,promise
I use GSAP library for animation. I am trying to wrap it by promises: $().promise().then(function() { var timeline = new TimelineMax(); timeline.to( $('.box'), 0.5, {css: {boxShadow: '0 0 40px 40px red'}}, 'box' ) .to($('.box'), 0.5, {css: {boxShadow: 'none'}}, 'box+=5') }) .then(console.log(1)) But, console.log run at start. How to fix it?...

Why doesn't my Deferred run the error method?

javascript,promise,ecmascript-6
I have created this simple code to simulate resolve , reject , error : function $http(){ var core = { factory : function (action) { var promise = new Promise( function (resolve, reject) { if (action==='resolve') resolve({r:'Resolved'}); if (action==='error') throw Error("error"); if (action==='reject') reject({r:'Reject'}); }); return promise; } }; return...

Executing promises in sequence: understanding a claim made about this example code

javascript,promise,ecmascript-6
I'm not looking for a solution for how to execute promises in sequence, I'm trying to understand the one given by a blog author: I am reading "We have a problem with promises" by Nolan Lawson, posted 18 May 2015. Under "Advanced mistake #3: promises vs promise factories" he has...

Promise chain breaking

javascript,promise,bluebird,spread
I have a promise chain (bluebird) that breaks up, and I can't figure out why. Promise.resolve() .then(function() { [..] }) .then(function() { [..] }) .then(function() { [..] }) .spread(function(instance) { [..] }) This fails with TypeError: undefined is not a function on .spread. A console.log on the last .then() show...

how to return a promise when waiting for another promise before that

javascript,promise,bluebird
My view-model gives a call to a service A and that service A needs to call another service B. the B will return some value that is required by service A. But this seems not working. Here is my code. class BillingService { rest: BaseRest; baseUrl: string; configurationService: ConfigurationService; constructor()...

function sequence not getting executed as expected when dealing with jquery promise

javascript,jquery,angularjs,promise
I have some set of code which I want to execute once a function gets completed and this set of steps and functions will be called on click of a button. Below is my code: $scope.activetab = function (tabname, $event) { $.when(function () { showLoader(); alert('done'); }).done(function () { alert('next');...

Parse promise returns empty object

javascript,jquery,parse.com,promise
I'm iterating an array, but with each iteration, I'm calling an async method. Here is the code var getTaskResponse = function(displayedWidgetId) { var promises = []; // var promise = new Parse.Promise(); jQuery.ajax({ type: "POST", url: 'https://api.parse.com/1/functions/getWidgetResponse', data: { "groupWidgetId": displayedWidgetId }, beforeSend: function(request) { request.setRequestHeader("X-Parse-Application-Id", parse_ids.app_id); request.setRequestHeader("X-Parse-REST-API-Key", parse_ids.rest_api); }...

How to turn jQuery $.get into Bluebird thenable?

jquery,ajax,get,promise,bluebird
I want to GET with jQuery and thenable it's result but then is never happening; why? Of course I get my JSON response back. Below is full code: var Promise = require('bluebird'); new Promise(function (resolve, reject) { return $.get(url.address, url.options, 'json'); }).then(function (result) { console.log(result); }); ...

How does Q.all work in NodeJS?

javascript,node.js,promise,q
I have the following code: var a = [1,2,3,4,5]; var promises = []; a.forEach(function(item,index){ var deferred = Q.defer(); doSomething().then(function(){ deferred.resolve(true); promises.push(deferred); }); }); Q.all(promises).then(function(data){ console.log("something!!"); }); How does Q.all know that promises array has all the promises required by forEach loop? Sometimes, my Q.all runs before forEach. Please tell me...