q

Replacing callbacks with promises in Node.js

丶灬走出姿态 提交于 2019-11-27 10:07:48
I have a simple node module which connects to a database and has several functions to receive data, for example this function: dbConnection.js: import mysql from 'mysql'; const connection = mysql.createConnection({ host: 'localhost', user: 'user', password: 'password', database: 'db' }); export default { getUsers(callback) { connection.connect(() => { connection.query('SELECT * FROM Users', (err, result) => { if (!err){ callback(result); } }); }); } }; The module would be called this way from a different node module: app.js: import dbCon from './dbConnection.js'; dbCon.getUsers(console.log); I

Promises: Repeat operation until it succeeds?

时光毁灭记忆、已成空白 提交于 2019-11-27 08:36:58
I want to perform an operation repeatedly, with an increasing timeout between each operation, until it succeeds or a certain amount of time elapses. How do I structure this with promises in Q? Benjamin Gruenbaum All the answers here are really complicated in my opinion. Kos has the right idea but you can shorten the code by writing more idiomatic promise code: function retry(operation, delay) { return operation().catch(function(reason) { return Q.delay(delay).then(retry.bind(null, operation, delay * 2)); }); } And with comments: function retry(operation, delay) { return operation(). // run the

JavaScript promises and if/else statement

两盒软妹~` 提交于 2019-11-27 07:54:54
问题 When I use filemanager function for directory ( / ) code works well, but when I call file ( /index.html ) code returns an error. I see that the problem in if/else statement ( readdir runs even if isDir returned false ), but I don't know how correctly use it with promises. var fs = require('fs'), Q = require('q'), readdir = Q.denodeify(fs.readdir), readFile = Q.denodeify(fs.readFile); function isDir(path) { return Q.nfcall(fs.stat, __dirname + path) .then(function (stats) { if (stats

How to chain a variable number of promises in Q, in order?

别说谁变了你拦得住时间么 提交于 2019-11-27 06:44:56
I have seen Chaining an arbitrary number of promises in Q ; my question is different. How can I make a variable number of calls, each of which returns asynchronously, in order? The scenario is a set of HTTP requests, the number and type of which is determined by the results of the first HTTP request. I'd like to do this simply. I have also seen this answer which suggests something like this: var q = require('q'), itemsToProcess = ["one", "two", "three", "four", "five"]; function getDeferredResult(prevResult) { return (function (someResult) { var deferred = q.defer(); // any async function

asynchronous or promised condition for array filter

丶灬走出姿态 提交于 2019-11-27 06:29:03
问题 I need to filter an array based on a condition that can only be checked asynchronously. return someList.filter(function(element){ //this part unfortunately has to be asynchronous }) Is there any nicer way to do it with promises than what I already have? This snippet uses Q for promises, but you can actually assume any proper promises implementation. return q.all(someList.map(function (listElement) { return promiseMeACondition(listElement.entryId).then(function (condition) { if (condition) {

Produce a promise which depends on recursive promises

让人想犯罪 __ 提交于 2019-11-27 05:30:20
I have an array of integer ids, such as var a=[1,2,3,4,5] and I have a need to perform asynchronous remote calls for each of these ids. Each call is a WebAPI request performed using $resource and presented as promise. I need to create a function that takes array of these IDs, then initializes recursive promises chain. The chain should result in consequential webapi calls for each of IDs, one by one. These calls should not be parallel but chained. The function in question returns itself a "main" promise that should be resolved or rejected based on result of asynchronous web calls. That is, if

What happens if i reject / resolve multiple times in Kriskowal's q?

二次信任 提交于 2019-11-27 05:14:12
I'm studying the promises pattern and using kriskowal's q for node.js, having this snippet: var deferred = Q.defer(); try { messageData = JSON.parse(message); } catch (e) { global.logger.warn('Error parsing JSON message.'); deferred.reject(e); } ... if (some_reason) deferred.resolve(something); ... return deferred.promise; What if both the parser fails and some_reason is true? Will the execution procede from rejecting through resolving and both promise's method be called at different times, thus generating a bug? Should i avoid to call reject/resolve multiple times? Since promises can only

How do I sequentially chain promises with angularjs $q?

梦想的初衷 提交于 2019-11-27 04:32:07
In the promise library Q , you can do the following to sequentially chain promises: var items = ['one', 'two', 'three']; var chain = Q(); items.forEach(function (el) { chain = chain.then(foo(el)); }); return chain; however, the following doesn't work with $q : var items = ['one', 'two', 'three']; var chain = $q(); items.forEach(function (el) { chain = chain.then(foo(el)); }); return chain; Redgeoff, your own answer is the way I used to translate an array into a chained series of promises. The emergent de facto pattern is as follows : function doAsyncSeries(arr) { return arr.reduce(function

Recursive Promises?

血红的双手。 提交于 2019-11-27 02:45:57
问题 I would like to iterate over all files located in the HTML 5 file system and have some event get started once the iteration is complete. Since this is async + promises im having a hard time trying to grasp how it should work. I am using a angularJS and have created a service to encapsulate html 5 file system specific features. This is the recursive function: function walkDirectory(path) { fileSystem.getFolderContents(path) //this is the services and it returns a promise containing all files

How can I limit Q promise concurrency?

一曲冷凌霜 提交于 2019-11-27 02:43:49
问题 How do I write a method that limits Q promise concurrency? For instance, I have a method spawnProcess . It returns a Q promise. I want no more than 5 process spawned at a time, but transparently to the calling code. What I need to implement is a function with signature function limitConcurrency(promiseFactory, limit) that I can call like spawnProcess = limitConcurrency(spawnProcess, 5); // use spawnProcess as usual I already started working on my version, but I wonder if anyone has a concise