All Questions
6,641
questions
3162
votes
34
answers
2.2m
views
Using async/await with a forEach loop
Are there any issues with using async/await in a forEach loop? I'm trying to loop through an array of files and await on the contents of each file.
import fs from 'fs-promise'
async function ...
871
votes
24
answers
327k
views
How do I convert an existing callback API to promises?
I want to work with promises but I have a callback API in a format like:
1. DOM load or other one time event:
window.onload; // set to callback
...
window.onload = function() {
};
2. Plain ...
309
votes
14
answers
197k
views
Is Node.js native Promise.all processing in parallel or sequentially?
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 ...
285
votes
9
answers
653k
views
Why is my asynchronous function returning Promise { <pending> } instead of a value?
My code:
let AuthUser = data => {
return google.login(data.username, data.password).then(token => { return token } )
}
And when i try to run something like this:
let userToken = AuthUser(...
263
votes
6
answers
110k
views
Difference between microtask and macrotask within an event loop context
I've just finished reading the Promises/A+ specification and stumbled upon the terms microtask and macrotask: see http://promisesaplus.com/#notes
I've never heard of these terms before, and now I'm ...
253
votes
1
answer
71k
views
Are there still reasons to use promise libraries like Q or BlueBird now that we have ES6 promises? [closed]
After Node.js added native support for promises, are there still reasons to use libraries like Q or BlueBird?
For example if you are starting a new project and let's assume in this project you don't ...
238
votes
7
answers
37k
views
When is .then(success, fail) considered an antipattern for promises?
I had a look at the bluebird promise FAQ, in which it mentions that .then(success, fail) is an antipattern. I don't quite understand its explanation as for the try and catch.
What's wrong with the ...
233
votes
5
answers
94k
views
How to find which promises are unhandled in Node.js UnhandledPromiseRejectionWarning?
Node.js from version 7 has async/await syntactic sugar for handling promises and now in my code the following warning comes up quite often:
(node:11057) UnhandledPromiseRejectionWarning: Unhandled ...
198
votes
5
answers
69k
views
Is it bad practice to have a constructor function return a Promise?
I'm trying to create a constructor for a blogging platform and it has many async operations going on inside. These range from grabbing the posts from directories, parsing them, sending them through ...
196
votes
8
answers
213k
views
How to pass parameter to a promise function
this might seem a silly question but I am a newbie in this topic. I am working on promises on node js. And I want to pass parameter to a promise function. However I could not figure it out.
...
182
votes
10
answers
175k
views
How to promisify Node's child_process.exec and child_process.execFile functions with Bluebird?
I'm using the Bluebird promise library under Node.js, it's great! But I have a question:
If you take a look at the documentation of Node's child_process.exec and child_process.execFile you can see ...
179
votes
3
answers
64k
views
Placement of catch BEFORE and AFTER then
I have trouble understanding the difference between putting .catch BEFORE and AFTER then in a nested promise.
Alternative 1:
test1Async(10).then((res) => {
return test2Async(22)
.then((res) ...
174
votes
4
answers
123k
views
How do I properly test promises with mocha and chai?
The following test is behaving oddly:
it('Should return the exchange rates for btc_ltc', function(done) {
var pair = 'btc_ltc';
shapeshift.getRate(pair)
.then(function(data){
...
169
votes
8
answers
542k
views
Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai
So, I'm testing a component that relies on an event-emitter. To do so I came up with a solution using Promises with Mocha+Chai:
it('should transition with the correct event', (done) => {
const ...
162
votes
4
answers
308k
views
Node JS Promise.all and forEach
I have an array like structure that exposes async methods. The async method calls return array structures that in turn expose more async methods. I am creating another JSON object to store values ...
157
votes
8
answers
119k
views
Handling multiple catches in promise chain
I am still fairly new to promises and am using bluebird currently, however I have a scenario where I am not quite sure how to best deal with it.
So for example I have a promise chain within an ...
152
votes
9
answers
101k
views
Understanding promises in Node.js
From what I have understood there are three ways of calling asynchronous code:
Events, e.g. request.on("event", callback);
Callbacks, e.g. fs.open(path, flags, mode, callback);
Promises
I found the ...
130
votes
4
answers
89k
views
Why is 'this' undefined inside class method when using promises? [duplicate]
I have a javascript class, and each method returns a Q promise. I want to know why this is undefined in method2 and method3. Is there a more correct way to write this code?
function MyClass(opts){
...
120
votes
13
answers
142k
views
Correct way to write loops for promise.
How to correctly construct a loop to make sure the following promise call and the chained logger.log(res) runs synchronously through iteration? (bluebird)
db.getUser(email).then(function(res) { ...
120
votes
24
answers
143k
views
Promise Retry Design Patterns
Pattern that keep on retrying until the promise resolves (with delay and
maxRetries).
Pattern that keeps on retrying until the condition
meets on the result (with delay and
maxRetries).
A memory ...
113
votes
3
answers
233k
views
Promise.all().then() resolve?
Using Node 4.x. When you have a Promise.all(promises).then() what is the proper way to resolve the data and pass it to the next .then()?
I want to do something like this:
Promise.all(promises).then(...
106
votes
6
answers
116k
views
nodejs - How to promisify http.request? reject got called two times
I'm trying to wrap http.request into Promise:
new Promise(function(resolve, reject) {
var req = http.request({
host: '127.0.0.1',
port: 4000,
method: 'GET',
path: ...
105
votes
6
answers
55k
views
How to specify resolution and rejection type of the promise in JSDoc?
I have some code that returns a promise object, e.g. using Q library for NodeJS.
var Q = require('q');
/**
* @returns ???
*/
function task(err) {
return err? Q.reject(new Error('Some error')) :...
98
votes
3
answers
115k
views
How to handle the if-else in promise then?
In some case, when I get a return value from a promise object, I need to start two different then() precesses depend on the value's condition, like:
promise().then(function(value){
if(//true) {
...
95
votes
8
answers
97k
views
Replacing callbacks with promises in Node.js
I have a simple node module which connects to a database and has several functions to receive data, for example this function:
dbConnection.js:
import mysql from 'mysql';
const connection = mysql....
91
votes
2
answers
126k
views
return value after a promise [duplicate]
I have a javascript function where I want to return the value that I get after the return method.
Easier to see than explain
function getValue(file){
var val;
lookupValue(file).then(function(...
87
votes
13
answers
125k
views
using async await and .then together
Is there any harm in using async/await and .then().catch() together such as:
async apiCall(params) {
var results = await this.anotherCall()
.then(results => {
//do any results ...
86
votes
8
answers
104k
views
NodeJS Timeout a Promise if failed to complete in time
How can I timeout a promise after certain amount of time?
I know Q has a promise timeout, but I'm using native NodeJS promises and they don't have .timeout function.
Am I missing one or its wrapped ...
85
votes
8
answers
82k
views
Are nested promises normal in Node.js?
The problem I have been struggling with for two weeks now while learning Node.js is how to do synchronous programming using node. I found that no matter how I try to do things sequentially I always ...
82
votes
14
answers
95k
views
While loop with promises
What would be the idiomatic way to do something like a while loop with promises. So:
do something
if the condition still stands do it again
repeat
then do something else.
dosomething.then(...
79
votes
8
answers
70k
views
Native Support for Promises in Node.js
Is there native support for promises in current versions of Node.js?
Node.js uses the V8 engine. This JavaScript engine is also used by Chrome, and Chrome 32 has native support for promises. But I ...
70
votes
5
answers
79k
views
How to wait for a stream to finish piping? (Nodejs)
I have a for loop array of promises, so I used Promise.all to go through them and called then afterwards.
let promises = [];
promises.push(promise1);
promises.push(promise2);
promises.push(promise3);
...
68
votes
5
answers
103k
views
Catching Errors in JavaScript Promises with a First Level try ... catch
So, I want my first level catch to be the one that handles the error. Is there anyway to propagate my error up to that first catch?
Reference code, not working (yet):
Promise = require('./framework/...
68
votes
5
answers
31k
views
Why is `.catch(err => console.error(err))` discouraged?
I'm using promises and have code that looks like the following:
function getStuff() {
return fetchStuff().then(stuff =>
process(stuff)
).catch(err => {
console.error(err);
});
}
...
63
votes
4
answers
69k
views
for await of VS Promise.all
Is there any difference between this:
const promises = await Promise.all(items.map(e => somethingAsync(e)));
for (const res of promises) {
// do some calculations
}
And this ?
for await (const ...
61
votes
1
answer
10k
views
Koa / Co / Bluebird or Q / Generators / Promises / Thunks interplay? (Node.js) [closed]
I'm investigating building a web app in part with Koa, but I don't quite have a handle on the hows, whens, and whys of choosing between - and applying - the range of supportive "making async easier" ...
60
votes
1
answer
25k
views
Promise. What is the difference between return resolve() and resolve()?
somewhere read this example:
return new Promise( (resolve, reject) => {
fs.readFile(file, (err, data) => {
if (err) reject(err)
return resolve(data)
})
})
but I usually do this:
...
59
votes
11
answers
145k
views
async await with setInterval
function first(){
console.log('first')
}
function second(){
console.log('second')
}
let interval = async ()=>{
await setInterval(first,2000)
await setInterval(second,2000)
}
interval();
...
59
votes
4
answers
14k
views
Convert promise to bluebird
I found an existing library that uses promises, however it doesn't use bluebird. The library functions don't come with all the extra features bluebird does like .map() or .tap(). How do I convert a "...
57
votes
4
answers
41k
views
Promise callbacks returning promises
With regard to these great two sources: NZakas - Returning Promises in Promise Chains and MDN Promises, I would like to ask the following:
Each time that we return a value from a promise fulfillment ...
52
votes
2
answers
18k
views
JavaScript asynchronous programming: promises vs generators
Promises and generators allow you to write asynchronous code. I do not understand why both of these mechanisms are introduced in ECMA script 6. When is it best to use the promises, and when the ...
49
votes
2
answers
29k
views
Does async/await blocks event loop? [duplicate]
I was reading Don't Block the Event Loop from the Node.js guide. There was a line saying:
You should make sure you never block the Event Loop. In other words,
each of your JavaScript callbacks ...
49
votes
6
answers
45k
views
How to use promise.allSettled with typescript?
Typescript build is failing as it does not seem to like Promise.allSetttled even though I have set ts config comilerOptions with "lib": [ "ES2020.Promise" ],
It seems as though the ...
48
votes
6
answers
82k
views
How to use mongoose Promise - mongo
Can someone give me an example on how to use a Promise with mongoose. Here is what I have, but its not working as expected:
app.use(function (req, res, next) {
res.local('myStuff', myLib.process(...
47
votes
7
answers
138k
views
Using Promises with fs.readFile in a loop
I'm trying to understand why the below promise setups don't work.
(Note: I already solved this issue with async.map. But I would like to learn why my attempts below didn't work.)
The correct ...
47
votes
8
answers
31k
views
How do I promisify the AWS JavaScript SDK?
I want to use the aws-sdk in JavaScript using promises.
Instead of the default callback style:
dynamodb.getItem(params, function(err, data) {
if (err) console.log(err, err.stack); // an error ...
46
votes
3
answers
56k
views
Why do I need to await an async function when it is not supposedly returning a Promise?
Consider this code:
async function load() {
const data = await new Promise(resolve => {
setTimeout(() => resolve([1, 2, 3]), 10);
}).then(data => data.map(i => i * 10));
console....
46
votes
7
answers
74k
views
How to do promise.all for array of array of promises?
I am trying to run array of functions parallel and when everybody finishes I want work on that result.
I am using promises. Now, I can put all functions in an array and can do
Promise.all(array of ...
46
votes
3
answers
25k
views
Why are my JS promise catch error objects empty?
Preface:
Using Mongoose
Using Bluebird and replacing mpromise inside of Mongoose
The req.helpers.consoleMessage function seen bellow is a function with some simple logic in it that determines when to ...
45
votes
5
answers
55k
views
Test if a promise is resolved or rejected with Jasmine in Nodejs
I know how to do it in Mocha but want to know how to do it with Jasmine.
I tried this
describe('test promise with jasmine', function() {
it('expects a rejected promise', function() {
...