FAQ Database Discussion Community


mongoose how to populate non-id field or how to implement parallel promise population manually

node.js,mongoose,promise,generator,bluebird
I want to populate a non-id field with mongoose, and already found these questions here: link1 link2 It turns out that mongoose didn't support this functionality now. The open issue here:https://github.com/Automattic/mongoose/issues/2562 So now, I want to populate manually with extra queries. But I have some problems in doing it I...

How to use promise bluebird in nested for loop?

node.js,parse.com,promise,bluebird
I need to use bluebird in my code and I have no idea how to use it. My code contains nested loops. When the user logs in, my code will run. It will begin to look for any files under the user, and if there are files then, it will...

How would I structure a complex if / then chain with promises?

coffeescript,promise,bluebird
Specifically, bluebird compatible promises pseudo code is shown below if authentication db.findUser(authentication.userId).then (dbUser) -> sessionLogin dbUser # Done! else if isSession req.user db.findUser(req.user.id).then (dbUser) -> db.addUserAuth(req.user.id, authentication).then (dbAuth) -> return else db.createUser(userDetails).then (dbUser) -> db.addUserAuth(dbUser.id, authentication).then (dbAuth) -> return # Once all of that is done, do the following if...

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: [...

Bluebird nested promises with each/spread

javascript,coffeescript,mongoose,promise,bluebird
I'm facing an issue while using bluebird Promises. I'm using CoffeeScript but JavaScript answers are welcome too :) Here is what I'm trying to do : Code example Promise = require 'bluebird' Model = Promise.promisifyAll(require '[...]') # mongoose model promisified getOpts = () -> [...] # whatever Promise.each [1..3], (number)...

Why are consequent chained promises resolved?

javascript,node.js,promise,bluebird
I am trying to get my head around Promises/A+ and I am confused on a couple of points. Consider this: function foo() { console.log("In 'foo' function: --> which returns a Promise"); return new Promise(function (resolve, reject) { resolve() }); } var promise1 = foo(); var promise2 = promise1.then(function () {...

Thinking in JavaScript promises (Bluebird in this case)

javascript,node.js,asynchronous,promise,bluebird
I'm trying to get my head around some not quite so trivial promise/asynchronous use-cases. In an example I'm wrestling with at the moment, I have an array of books returned from a knex query (thenable array) I wish to insert into a database: books.map(function(book) { // Insert into DB });...

how to ensure request is done sequentially?

bluebird,requestjs
I'd like to request one page after another, the following code seems request all the pages in the same time, is there a way to fetch one page after the previous one is done? thanks var Promise = require("bluebird"); var request = Promise.promisifyAll(require('request')); var URLS = ["http://sample.com/j1", "http://sample.com/j2"] Promise.map(URLS, function...

Nested Promise in Promise each

javascript,node.js,promise,sails.js,bluebird
Can someone explain why this doesn't work as I expect it? I am trying to return only the id of the created or updated items to use in the Promise.each().then(). This is necessary because create returns an object and update an array of objects. Promise.each(items, function(item){ if(...item doesn\'t exist...) return...

Promise: What happens to other async request when errors are thrown?

javascript,promise,bluebird
I am using Bluebird promise. This isn't really explicit in the documentation. Suppose the following, assuming all the instances are appropriate promises: FindSomeDBModel.then(function(model) { return [ model.getOtherModels(), aHTTPRequest('https://google.com') ]; }).spread(function(otherModels, httpResponse) { // some code }).catch(function(err) { res.status(500).send(err); }); If both model.getOtherModels and aHTTPRequest throws an error, what will be...

Unit testing promise based code in node.js express route/controller

node.js,unit-testing,express,promise,bluebird
Recently I switched from using callbacks to using promise in my rest api express app. But I'm having trouble with unit testing routes/controller with async behaviour of the promise. Here is the sample code that needs to be unit tested. var handler = function (req, res, next) { var query...

How can I do pagination with Bluebird Promises?

javascript,node.js,promise,bluebird
I have something like new Promise (resolve, reject) -> trader.getTrades limit, skip, (err, trades) -> return reject err if err resolve trades .each (trade) -> doStuff trade limit is set to some arbitrary number, say 10 and skip starts at 0. I want to keep increasing skip until there are...

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...

Waiting for the end of a recursive readdir function

javascript,node.js,recursion,promise,bluebird
i'm using a recursive readdir to read the whole file tree of a directory to put it into a database. My problem is that i'm trying to stop the next lines of code while the whole readdir / insert to the database isn't finished. I was looking for a solution...

Wrap Bluebird promise in mPromise

mongoose,promise,bluebird
I am using mPromises throughout a service and in order to maintain a consistent interface (i.e end() for ex) I have a need to wrap a promisfied Bluebird function in it - I am not too familiar with mPromise though and am not succeeding. Here's what I have: var p...

Convert nested 'for' loops into a Promise, for a Promise? Nested Promises?

javascript,node.js,promise,bluebird
I have an array where the values are sequences separated by '/', and a 'mapSeries' Promise (helper function for serially iteration with mapping) that loops through each value within each of the sequences. Right now, the statement starts with a nested 'for' loop that splits a sequence into strings, and...

Typescript and resolving promises without the use

javascript,typescript,promise,bluebird
How can I make the resolve(<any>existingVote) to compile without the <any >. If I remove the <any> I get Argument of type 'Object' is not assignable to parameter of type 'Thenable <Object> in the compiler error window. It seems I may not understand yet how to create a Thennable <Object>...

Bluebird Promise.all callback error

javascript,promise,bluebird
im trying to process an array using Promise.all(), but i can't, here is the code: this function request info a imdb module.exports = { info: function(name, fn){ var MovieDB = require("moviedb")("470fd2ec8853e25d2f8d86f685d2270e"), path = require("path"); var rex = /([a-z]*\b(?:m2ts|mp3|sub|spanish|english|french|brrip|gaz|yify|avi|mp4|mkv|bdrip|dvdrip|dvdscr|dvdscreener|screener|dvdrip|r5|telesync|480p|480i|576p|576i|720p|720i|1080p|1080i|hrhd|hrhdtv|hddvd|bluray|x264|h264|xvid|ac3|dts|aac))/ig name = path.basename(name) name =...

Calling object methods with promises and the 'this' context [duplicate]

javascript,bluebird
This question already has an answer here: Object method with ES6 / Bluebird promises 2 answers I understand that in Javascript objects, the this keyword is not defined by declaration, but by invocation. So I am wondering how we can avoid the following problem: var testObject = function(){ this.foo...

Breaking up promise chain

javascript,promise,bluebird
Why are these not equivalent and is there a way to make them so? // Returns result of promiseB var p = self.promiseA() .then(self.promiseB); return p; // Returns result of promiseA var p = self.promiseA(); p.then(self.promiseB); return p; For example if I wanted to do something like: var p =...

How to reuse a mongo connection with promises

javascript,mongodb,promise,bluebird
How can I change things around in my db connection call so that I can do db.collection(): // Create a Mongo connection Job.prototype.getDb = function() { if (!this.db) this.db = Mongo.connectAsync(this.options.connection); return this.db; }; // I want to be able to do this Job.prototype.test = function() { return this.db.collection('abc').findAsync()... };...

Thrown error in promisified ExpressJs function

javascript,node.js,express,bluebird
I'm not quite sure I understand how errors are handled in promises (and I'm fairly new to promises so I'm likely not using them to their full potential). I have the following code: app.listenAsync = Promise.promisify(app.listen); app.listenAsync(config.port) .then(function done() { console.log("We're listening!"); }) .catch(function (err) { console.log("Abort abort!"); }); For...

Meteor with Promises

javascript,meteor,promise,bluebird
I've been trying to get into the habit of using promises but ran into problems while trying to use them in server side code in the context of Meteor. This is the problem: if (Meteor.isServer) { Meteor.startup(function () { // code to run on server at startup p = function(){...

Node.js 'Object is not a function' for payload() on second run

node.js,bluebird
This code is to where a user enters their username/password they get a token back. I have it to where if they enter the wrong info and get a 401, they get the prompt again to try again with .catch(function(err) { callApiToken(); }). However, on the second pass I will...

next() promise error handling

node.js,express,mongoose,promise,bluebird
What would be the optimal way for error handling? I need custom json error messages. It's an API. exports.putCurso = function (req, res, next) { util.updateDocument(req.curso, Curso, req.body); req.curso.saveAsync() .then(function (data) { return res.status(201).json({message: 'Curso atualizado.', data: data}); }) .catch(function(error) { return res.status(500).json({message: 'ERROR!'}); //OR return next(error); but I need...

How to turn callback function with Promise

javascript,node.js,promise,bluebird
I'm using Bluebird promises and trying to get below function with Promisify working: var jwt = require('jsonwebtoken'); function _test_encode() { var cert = fs.readFileSync('public.pub'); return jwt.verify(token, cert, function(err, decoded) { console.log(decoded); }); } I tried below: var jwt = require('jsonwebtoken'); var Promise = require('bluebird'); var jwtVerifyAsync = Promise.promisify(jwt.verify); function _test_encode()...

Save changing variables for promises

javascript,node.js,promise,bluebird
I am using promises for my database access (elasticsearchjs, which uses Bluebird). For each ID in my list im am starting a new query. Now I want to know the ID of the element when the query fails. var idList = ['id1', 'id2', 'id3', '...']; var promises = []; for...

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...

Creating throttling function with Bluebird promises

javascript,promise,bluebird
I am attempting to created a throttling function. I have looked at a few SO posts and copied some code but I am unable to get it to delay. Basically I have a number of methods in a class that need to call the Amazon API. They all make use...

Promise.map not finshing because subsequent Promise.join finishes first? Promise.all?

javascript,node.js,mongoose,promise,bluebird
Am still getting the hang of promises.. Here are the models of the db collections involved: var itemSchema = new Schema({ label : String, tag : { "type": Schema.ObjectId, "ref": "tag" } }); var tagSchema = new Schema({ label : String, }); And here's the series of Promises (map, map,...

Node function runs before promise.then() completes.

node.js,promise,bluebird
Shouldn't foo run after refreshToken is complete? Right now foo runs before foo is completed. function refreshToken() { var tokenFile = path.join(__dirname, 'token-file.json'); return fs.readFileAsync(tokenFile, {encoding: 'utf-8'}) .then(function(tokenString) { token = JSON.parse(tokenString); }).catch(function(err) { console.log("No token-file.json file found. " .red + "Please complete for a new one." .red); createTokenFile(); });...

Use Superagent with A+ spec?

javascript,node.js,promise,bluebird,superagent
How can I use Superagent but with the Promises A+ spec? I'm working on a project that uses both Superagent and Bluebird and I would like to use the .then() syntax but can't figure out an easy way to do this without writing my own wrapper code. I see this...

Optional promise-step based on query parameter

javascript,mongoose,promise,bluebird
I've got a function retrieving blog-posts from the database. The same function is used for blog-posts of a certain category. This is the query: Post.find( params ).limit(5) However when a category shall be looked up, the id of the category has to be retrieved first (the query-param is its permalink):...

Bluebird promise `promisifyAll` not working - cannot read property `then`

xml-parsing,callback,promise,bluebird,node-modules
I am using a node module that uses the node callback convention. I wants to convert this module into an API using Bluebird promises. I am not getting how to do this. Below is my node style callback function. I wants to convert it into thenable promise of bluebird. var...

Why can't I pass Node request methods directly to Bluebird promises? [duplicate]

javascript,node.js,promise,bluebird
This question already has an answer here: Why cant I inline call to res.json? 1 answer It should be entirely possible to run something like the following: function someMiddleware (req, res, next) { someAsyncBluebirdOperation().then(res.json); } But if you pass any methods of a res objects directly as a reference...

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...

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

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

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},...

How do I chain multiple promises?

javascript,node.js,promise,bluebird,fs
I'm not quite sure, and maybe I'm missing something obvious, but I cannot figure out how to chain two promises. My callback-based code looks something like this: async.series([ function (cb) { // Create the directory if the nodir switch isn't on if (!nodir) { fs.mkdir('somedirectory', function (err) { if (err)...

How do I access promise result later on? [duplicate]

javascript,promise,bluebird
This question already has an answer here: How do I access previous promise results in a .then() chain? 6 answers var screencastId = 'abc' var a = youtube.get(screencastId); a.then(function(screencast) { // Yay. I have the screencast information here. console.log(screencast); }); // How do I access the `screencast` variable down...

Promise chaining and error handling

javascript,node.js,error-handling,promise,bluebird
I'm trying to understand chaining and error handing with promises. Here I have some promise chained. return ad_fetcher.getAds(live_rail_url, ad_time, req.sessionID) .spread(generator.playlist_manipulate) // returns Promise.resolve([data, anotherData]) .then(client.incrAsync(config.channel_name + ":ad_hits", "vdvd")) // FOCUS HERE .then(function() { console.log("AD FETCHED AND PLAYLIST GENERATED."); res.send(generator.generate_regular(config.default_bitrate)); }) .catch(function(err) { console.log('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');...

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...

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...

Bluebird promise and no method 'reject'

mongoose,promise,bluebird
I've promisified Mongoose with Bluebird. This code worked using mPromise but now yields the error: Object [object Promise] has no method 'reject' The code: var p = Order.findOneAsync(q).then(function(order) { return p.reject(Boom.badRequest()); This is overly simplified but the basics are there. How would I reject the promise?...

Promises to replace a callback gettin invoked multiple times [duplicate]

javascript,promise,bluebird
This question already has an answer here: One time event handling using promises? 2 answers I have method which does some stuff and invokes a callback and after certain time it does the same. var myFunction = function(callback){ setInterval(function(){ var stuff; //do some stuff callback(stuff) }, 3000); } Can...

Promise prevent node process from exiting

node.js,promise,bluebird
I write a tool for migrating data using Bluebird promise, so that user can trigger this tool directly via node command. Example: node migrate.js The problem is, this node process will not exist after complete. Here is the content of main migrate.js, the exec() function return a promise. var migrate...

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 );...

Efficiently composing promise tests

javascript,mocha,bluebird
I find myself often writing tests for async APIs like this: beforeEach(function(done) { setup() .then(function(val) { return setup2(); }) .done(done, done); }); it('should test something', function(done) { promiseFunction .then(function(val) { expect(val).to.be.something; }) .done(done, done); }); Which seems pretty straightforward, except for the beforeEach function: if setup2 returns a promise, then...

I'm trying to use the Bluebird's method Promisify and it's not working

javascript,asynchronous,promise,bluebird
I'm not able to make a simple example works on bluebird. I've used the new Promise method and it works, but when I try to use the Promisify method I may be doing something wrong. exports.makeRequest = function(someText){ return Promise.resolve(someText); } var makeRequestAsync = Promise.promisify(exports.makeRequest); makeRequestAsync('Testing').then(function(data){ console.log(data); // --> log...

Saving and Finding Mongoose Documents with Nested Schemata with Refs and Promises

javascript,node.js,mongodb,mongoose,bluebird
I have a fairly simple question. I'm trying to save a document whose schema includes a nested schema ref, and that schema ref includes another schema ref. When I go to retrieve that document, however, it does not include the (required) nested field unless I populate it in the same...

Calling async functions recursively

javascript,node.js,promise,bluebird
I need to have an async method eg. getWeather called forever with a small delay between the success of previous call and beginning of the next call. I have used a recursive function for the purpose. I am concerned if this can cause a performance hit. Are there any better...

Chaining timeouts results in last timeout rejected?

javascript,node.js,promise,q,bluebird
I'm currently trying to chain some promises with timeouts and no matter which timeout is reached it's always reporting the last one. I tried it with bluebird and Q with the same result, so I think I have a general problem. The code basically looks like this: var Promise =...

Recursion with Asynchronous Functions and Bluebird Promises in JavaScript

javascript,recursion,iteration,promise,bluebird
In JavaScript, I have four sets of functions: Set_A synchronousFunction_One synchronousFunction_Two synchronousFunction_Three synchronousFunction_Four synchronousFunction_Five Set_B objectA.asynchronousFunction_One objectA.asynchronousFunction_Two . . . objectA.asynchronousFunction_N Set_C objectA.asynchronousFunction_Three objectA.asynchronousFunction_Four . . . objectA.asynchronousFunction_M Set_D synchronousFunction_Six I need each set to be run one after another, in a particular order and with certain constraints: None of...

Bluebird promises - nesting vs rejecting pattern

javascript,mongoose,promise,bluebird
I'm working on an app for which we're using promises. I'm attempting to figure out what the better pattern is. Breaking up concerns between thenables and rejecting the promise if an error. Rejection is then handled in a catch block. Or is it better to throw a new type of...

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...

How do I properly write a module to be compatible with Bluebird's `PromisifyAll`

javascript,node.js,promise,bluebird
Let's say in a node.js module, moduleA.js, I have the following object with a bunch of node-style async functions: // moduleA.js var init = function (data, callback) { return callback(null, data.params ); }; var delay = function(data, callback) { setTimeout(function(){ callback(null, data); }, 1000*3); } var reverse = function(data, callback)...

Now to use Bluebird promises with Asana Node library?

bluebird,asana
I'm using the Asana Node library to create a new project with a series of sections (tasks) within the project. I need to create the sections in a specific order (synchronously) so they appear in the correct order in the project. If I just take an array of section names,...

How to confirm if update succeeds using mongoose and bluebird promise

javascript,node.js,mongodb,promise,bluebird
I'm using bluebird and mongoose for a node page. I want to check if the update is successful before sending data back to clients via socket.js.Here's the part of the code that I can't figure out: .then(function(a) { var g = collection3.update({ _id: a.one[0]._id }, { $set: { avg: a.one[0].avg...

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()...

How do I access 'this' inside of Promise.map?

javascript,node.js,promise,bluebird
As we know, this below refers to the window object. What I would like to know is how I can pass my this context in without resorting to the var self=this; trick. Any ideas? I tried adding .bind() to the end of line 9 so it reads }).bind(this); but that...

Trigger Promise when an event fires

node.js,promise,bluebird
My entire project uses (Bluebird) Promises, but there's one particular library that uses EventEmitter. I want to achieve something like: Promise.on('connect', function() { x.doSomething(); }).then(function() { return new Promise(function(resolve) { y.doAction(resolve); // this will result in `eventB` getting emitted }); }).on('eventB', function() { z.handleEventB(); }).then(function() { z.doSomethingElse(); }); I read...

Mongoose save with promises and populate

javascript,node.js,mongoose,promise,bluebird
I have the following code (Mongoose has been promisified with Bluebird) function createNewCourse(courseInfo, teacherName) { var newCourse = new courseModel({ cn: courseInfo.courseName, cid: courseInfo.courseId }); return newCourse.saveAsync() .then(function (savedCourse) { var newTeacher = new newTeacherModel({ na: teacherName, _co: savedCourse._id // This would be an array }); return newTeacher.saveAsync().then(function() { return...

bluebird recursive promise not getting resolved/fullfilled

javascript,node.js,promise,bluebird
Using BlueBird promises, I am trying to make getCredentials into a promise that will work as getCredentials.then(function() { do this and that } );. Not sure what I am doing wrong, because when I resolve in writeToFile the promise is not counted as resolved/fullfilled. function getPassword(user) { return new Promise(function(resolve,...

Promises and streams using Bluebird.js and Twitter stream

javascript,node.js,promise,bluebird
I am new super new to Promises and Node and am curious about using promises with streams. Can I promisify a stream? Using Bluebirdjs and the Twit module I have the following: var Twit = require('twit') var Promise = require("bluebird"); var T = new Twit({ consumer_key: process.env.CONSUMER_KEY, consumer_secret: process.env.CONSUMER_SECRET, access_token:...

Why can I get a Bluebird catch in the middle of chain stop the rest of the chain execution

javascript,promise,bluebird
I am building this promise chain. The goal is to have the first action check for uniqueness on a field in the DB, and then if unique, save the object. But if the object is not unique, it should not save, and should return an error response. function(request, reply) {...

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...

Is there a way to pass custom data in .then part of Promises?

javascript,promise,bluebird,bookshelf.js
I'm really new to promises (I'm using bluebird promises with expressjs). I like how they tidy up the code. However, I'm not quite sure how to use them in some scenarios. I'm not even sure I'm using them right in my example. The issue I have is that I'd like...

Implementing Promises using Bluebird

bluebird
I have a function which needs to be implemented with Bluebird Promises but unable to work it out. Here is a pseudo code exports.addEmployees=function (req,res){ var data = [ { firstName: 'XXXXX', lastName: 'V', phone: '9999999999', dateOfBirth: '2010-08-02', department: 'IT', startDate: '2015-08-02', created: now, updated: now }, { firstName: 'YYYYY',...

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...

Is there right way to store resolved promises?

javascript,node.js,promise,bluebird
Right now almost every node package has callback api. What if I'm writing wrapper around it, ORM for instance: const Promise = require('bluebird'); const mongo = Promise.promisifyAll(require('mongodb')); class ORM { constructor(mongoUrl) { this.db = mongo.connectAsync(mongoUrl); } collection(name) { return this.db.then((db) => { return db.collectionAsync(name); }); } } Is this right...

How to resolve a set of promises and values using Bluebird

javascript,promise,bluebird
I have a list values xs = [1, 2, 3, 4] I also have an asynchronous function square that returns a promise of the square of the argument passed to it. I want to pass the elements of my to list to my function in parallel, then collect the promises...

How to return a Mongoose object from saveAsync?

node.js,mongoose,promise,bluebird
I've promisified Mongoose with Bluebird - all seems to work fine except that documents returned by saveAsync() are just plain objects and lack methods/virtuals. order.saveAsync().then(function(order) { order.save(); // errors with object has no method 'save' I am using 'save' as an example but no builtin method or my custom methods...

Adding a method to Bluebird promise

promise,bluebird
I have promisified Mongoose. I have some methods that extent Mongoose Query that now would need to be added to Bluebird. I don't mind extending Mongoose but do not want to take the same approach for this more gobal library. Looking through the docs I see some potentials but I...

Express.js - foreach array of data and store them in the database

javascript,node.js,promise,bluebird,bookshelf.js
I'm using expressjs, bookshelf.js and I want to post array of data, foreach such data and save it. I'm not exactly sure where the issue is (express, bookshelf or just plain old javascript), but here's the scenario: when I post the said array and try to iterate through it, I...

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);?...

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...

how to use bluebird to promisify node-rest-client

javascript,node.js,bluebird
I'm trying to promisify the node-rest-client library (tried restler but seems not to be re-entrant and caused problems with parallel POSTs to same endpoint). I've tried to use a similar approach to the provided filter/promisifer shown in the bluebird docs for restler, however can't seem to get it working. node-rest-client...

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...

How to use Bluebird promisification with generators + parallel promises

arrays,generator,bluebird,koa,co
Trying to fire off mutiple requests off to the beats api using bluebird as well as koa for generators. After reading some documentation I figured the following would work var request = require('co-request'), _ = require('lodash'), Promise = require('bluebird'); request = Promise.promisifyAll(request); module.exports.getTracks = function *tracks(){ firstCall = yield makeAPICall('users/'...

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...

ES7 async/await conceptual issue

javascript,node.js,bluebird,ecmascript-7
I am migrating an existing program to use async/await (via Babel's bluebirdCoroutines) in order to learn this style. I have been looking at this tutorial. I am a bit troubled by the following behavior. This snippet works as expected: let parts = []; let urlsP = urls.map((url, index) => {...

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); }); ...

What is the promise disposer pattern?

javascript,promise,dispose,bluebird
I've read about the promise disposer pattern in several places but I can't figure out what it is. It was suggested to me to use it in code that looks like: function getDb(){ return myDbDriver.getConnection(); } var conn = getDb(); var users = getDb().then(function(conn){ return conn.query("SELECT name FROM users").finally(function(users){ conn.release();...

Promise findOneAsync variable = {“isFulfilled”:false,“isRejected”:false}?

javascript,node.js,mongoose,promise,bluebird
Utilizing Bluebird to Promisfy Mongoose, I have a Promise.map(function with a series of if/else for looping through an array to see if a reference doc exists, else create one.. Assigning the product of findOneAsync to a variable, to then assign 'variable._id' to a new doc in the making (the main...

Mocha testing a bluebird powered node style callback

javascript,node.js,mocha,sinon,bluebird
I am facing trouble to get pass a test by running mocha which seems to be passing. The test: describe('.get()',function() { it('should be called once',function() { // => Need to spy on this var callback = function(err,data) { console.log('I am called'); if (err) { console.log('I am logging the error '+err);...

Bluebird chain promises

javascript,node.js,bluebird
I'm using the bluebird library and need to make a series of HTTP requests and need to some of the response data to the next HTTP request. I've built a function that handles my requests called callhttp(). This takes a url and the body of a POST. I'm calling it...

Unhandled rejection in Bluebird

javascript,bluebird
I have the following code. It works fine when f2 throws no error. If there is an error, it generates an Unhandled rejection Error. What's the proper way to rewrite the code to avoid Unhandled rejection Error and propagate it correctly to catch in f1? let Bluebird = require('bluebird'), mkdirp...

Bluebird Promise serial iteration, and resolve to modified array?

javascript,node.js,promise,bluebird
I have this promise that creates a new Item document if it's not found in the db, and then stores it in a previously created Collection document.. The Collection document is the first string in an array, and any subsequent index in the array translates to one or more Item...

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 )....

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...

Bluebird .then(): no TypeError when function reference is undefined

javascript,node.js,promise,bluebird
I recently started working with promises and found a strange behavior for me. When i give the .then() function a reference to a undefined function it is just skipped and the next then is called. An example: var cust = customer({general: { cust_id: 22 }}); // just for testing req.pool.getConnectionAsync()...

How to extend Mongooose prototype with better saveAsync

javascript,mongoose,promise,bluebird
I am using mongoose with bluebird initializing with promisifyAll. It's cool and I'm loving promises. But mongoose's model.save() returns a function signature like (err, user, numAffected) so bluebird's model.saveAsync() returns a two-element array rather than the obvious result alone. This makes chaining inconvenient so I've taken to making little helper...

wrap node-multiparty with promisifyAll bluebird

node.js,bluebird
I'm new with node.js, I'm trying to wrap node-multiparty callbacks with bluebird but the parse function signature of multiparty is function(err, fields, files) and the promise signature requires just one return value. I'm sure there is a way to do this but I haven't found anything yet. Thanks in advance!...

Promisifying already promise based library with bluebird

javascript,node.js,promise,bluebird,io.js
If a library exposes a promise-based API that is not based on bluebird but does not expose a traditional callback API, is there a way to "promisify" that library to return bluebird promises? Currently I either just return the promise to a bluebird context, or if I want to use...

Recursive Promise Call- Memory Scope Variable Issue

javascript,node.js,promise,bluebird
I have these functions for the purpose of retrieving a token through a api call out. If the user enters the wrong password, the promise will reject and on reject the function is called again to give the user another try. If the user enters the right password the first...

Restify returns undefined is not a function in error object

javascript,node.js,bluebird,restify
I have a below Restify custom error that is being thrown to my catch block of BlueBird Promise. var test = function() { respObject = { hello: { world: 'aasas' } }; throw new restify.errors.ServiceError(respObject, 422); } Then in ServiceError: function ServiceError(respObject, statusCode) { restify.RestError.call(this, { restCode: 'ApiError', statusCode, statusCode,...

Catching errors with chai and promises

javascript,promise,bluebird,chai,chai-as-promised
I would like to know how to stop the console from printing stack dumps on test with promises that throw errors. doCallTest = function() { var p = new Promise(function(resolve, reject) { reject(new Error('Nooooo')); }).catch(function(err) { throw new Error(err); }); return Promise.delay(100).return(p); }; // This prints error message `Error: Nooooo`...

Concise way of chaining promise and passing value

javascript,promise,bluebird
What is the most concise way of writing this with Bluebird promises: return someFunc().then(function(result) { return otherFunc(result).then(function(foo) { ... }); }); I see some util functions such as result() but not totally clear how/which I would use. Basically I need to call the 2nd function while passing the result of...

Way to provide “this” to the global scope?

javascript,object,prototype,promise,bluebird
I'm working with a debounce function found here in this stackoverflow post. It's a promise that allows for throttling requests. The debounce function won't work for some reason when it's nested within a function because the setTimeout calls to the request seem to get sent all at once. It needs...

Iterating over an array and joining with Bluebird

javascript,bluebird
Is there a better way to write this? For the most part, the code below works, but I would like to clean it up if possible. For reference, outputs in the initial callback is an array of objects, containing the file path and some metadata. I would like to have...