Asynchronously pushing items to an array and saving with Node.js promises

I am currently attempting to populate an array (which is an attribute in a Mongo Model) with items received from a request. I iterate through these items to check if they already exist in the database, and if not, I create a new Item and attempt to save it. Although I am using promises to manage this process, I am puzzled as to why the array turns out empty even after all promises have been fulfilled.

var q      = require('q');
var items_to_get = ['1', '2', '3']; // example array
var trans  = new Transaction({
    items   : []
});
var promises = [];

for (var i = 0; i < items_to_get.length; i++) {
    var ith = i;
    var deferred = q.defer();
    
    Item.findOne({simcode: items_to_get[ith]}, function(err, item) {
        trans.items.push(item);
        deferred.resolve(item);
    });
    
    promises.push(deferred); 
};

q.allSettled(promises).then(function(result) {
    console.log(trans.items); 
    trans.save();
}

UPDATE Issue Resolved: Modified code below, inspired by http://jsbin.com/bufecilame/1/edit?html,js,output .. credits to @macqm

var items_to_get = ['1', '2', '3'];
var promises     = []; 

items_to_get.forEach(item) {
  upsertItem(item);
}

q.allSettled(promises).then(function(result) {
  result.forEach(function(res) {
    if (res.state === "fulfilled") {
      trans.items.push(res.value);
    }
  });
  trans.save();
  promises = [];
}

function upsertItem(item) {
  var deferred = q.defer(); 
  Item.findOne({simcode: item}, function(err, item) {
    deferred.resolve(item);
  });
  promises.push(deferred); 
}

Answer №1

I accomplished this task without relying on any external libraries.

Since I only needed to defer and I'm using ES2017, I decided to keep things simple and avoid unnecessary dependencies.

'use strict';

/**
 * @param {function(*)} func
 * @param {Array} arguments
 * @returns {Promise.<*>}
 */
const defer = (func, arguments) => {
    return new Promise(resolve => {
        resolve(func(...arguments));
    });
};

/**
 * @param {Number} num1
 * @param {Number} num2
 * @param {Number} duration
 * @returns {Promise.<Number>}
 */
const asyncFunction = (num1, num2, duration) => {
    return new Promise(resolve => {
        setTimeout(resolve, duration, num1 + num2);
    });
};

let promises = [];
promises.push(defer(asyncFunction, [3, 7, 0])); // returns immediately
promises.push(defer(asyncFunction, [10, 20, 100])); // returns after 100ms
promises.push(defer(asyncFunction, [55, 45, 50])); // returns after 50ms

Promise.all(promises).then(results => {
    console.log(results);
});

If you run the code above, you will receive the output: [ 10, 30, 100 ].

Answer №2

Instead of

insert.deferred(promises);

... consider using ...

insert.deferred.promise(promises);

In addition, since your promises are resolving to the item that was saved anyway, you can utilize the outcome of q.allSettled(...) as your items:

q.allSettled(insert.deferred).then(function(results) {
    transactions.list = results;
    transactions.save();
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experiencing difficulties with JWT implementation and seeking to transmit the JWT token to additional APIs

I am currently working on implementing JWT authentication in node js/express js: Below is the sample code I have written for this purpose: const jwt = require('jsonwebtoken'); const secretKey = crypto.randomBytes(64).toString('hex'); c ...

Unable to establish headers once they have been issued - routing error

I have come across various solutions for this problem, but I am struggling to resolve it on my own. Therefore, I am sharing my code here in hopes of receiving assistance. I am new to this and would appreciate any help in understanding and fixing the issue ...

Will modifying files in the node_modules directory trigger a restart of nodemon?

https://i.stack.imgur.com/3dJLt.png { "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node bin/server.js", "dev":"nodemon bin/server.js" }, "dependencies": { ...

What steps should I take to retrieve JSON data using fetch from my Express server?

After several attempts to use fetch for retrieving JSON data from my express server, I have encountered some issues. While the fetch function works well with JSONPlaceholder, it seems to fail when accessing my express code. Below is the snippet of my fetc ...

Issue with reading custom environment variables in a React application is preventing successful execution

I have an application that combines React with ASP.NET and is run from Visual Studio. However, I am encountering a perplexing error message: Error: The configuration file /config/custom-environment-variables.js cannot be read. Error code: undefined. E ...

jquery is showing up in the browserify bundle.js file, however, it is not functioning properly

Currently, I am trying to follow a brief tutorial on how to use Browserify. Despite following the instructions precisely, jQuery seems to not be working properly when bundled. Specifically, the button element in my app.js code is not appended to the body. ...

'An error occurred when invoking the class method due to 'This' being undefined

I'm attempting to display a response message to the user, but encountering an error (Cannot read property 'message' of undefined). Here's the code snippet causing the issue: server.js const server = express(); let App = require(' ...

What could be the reason for the lack of error handling in the asynchronous function?

const promiseAllAsyncAwait = async function() { if (!arguments.length) { return null; } let args = arguments; if (args.length === 1 && Array.isArray(args[0])) { args = args[0]; } const total = args.length; const result = []; for (le ...

Encountering errors while trying to install the npm package.json

For instance, I encountered an issue when trying to create a react project via npm. The error message indicated that it couldn't find my package.json file. Any assistance on resolving this would be highly appreciated. I will also share the process of ...

Encountering a console error: Prop type validation failed for the `Rating` component with the message that the prop `value` is required but is currently `undefined`

I am encountering a proptype error which is causing an issue with the URL display on my Chrome browser. Instead of showing a proper address, I am seeing the URL as undefined like this: http://localhost:3000/order/undefined Instead of undefined, I should h ...

"Using PHP to encode an array into JSON format might result in additional

My PHP array needs to be printed as clean JSON, but I'm encountering issues with extra quotes. While the current JSON output is technically valid, it's not formatted how I want it to be. Below you can see the original PHP array, the json_encode o ...

In AngularJS, modifying the value of a copied variable will result in the corresponding change in the value of the main

I'm facing a peculiar issue. I have an array of objects and I used angular.forEach to update the price key value of each object. However, when I make changes in each object, it also affects the main array object. Take a look at the code snippet below ...

What is the best way to fully eradicate an ECMAScript module within a nodejs environment?

In my electron project, users are required to modify the HOOK script, which can be immediately applied to nodejs. Below is the relevant code for this function: const {ipcMain} = require("electron") const ipc = require("./IPCCommands") ...

What is the best way to manage an assertion error in MongoDB when using Node.js?

mongo.connect('mongodb://localhost',{useUnifiedTopology: true}).then((client) => { var db = client.db('complainbox'); db.collection('admin').findOne({"Email":req.body.Email},(err,result)=&g ...

Encountering a syntax error when running newman on an Ubuntu system

Just starting out with newman and looking to integrate it into my CI\CD pipeline (specifically VSTS). I've been able to export my collection.json and env.json files, but running the tests is giving me some trouble. newman run Dev-.postman_collect ...

Trouble removing old version of create-react-app with npm global uninstallation procedure

After taking a long break, I decided to create a new React application today. However, when I used the command npx create-react-app, an error popped up: The version of `create-react-app` you are running is 4.0.3, which is not the latest release (5.0.0). G ...

Error: EPERM -4048 - the system is unable to perform the operation specified

Every time I attempt to install a package using npm install, I encounter an error message (usually referring to a different path). I have attempted running npm cache clean, restarting my computer, and checking for any processes that may be interfering with ...

What is the best way to transfer a "require" object to Jade in Node.js?

I have developed a node module that includes a simple JavaScript file. My goal is to utilize this JavaScript function within my jade file. In music.js, I am importing the "myplayer" module: var keystone = require('keystone'); exports = module.ex ...

AngularJS and Handlebars (npm)

Is it possible for angularJS to function as a substitute for the "view engine" in nodeJS? I am seeking insights on the optimal method to use. (Do MEAN Stack developers utilize view engines? Or do they prefer using res.sendFile along with tools like ui-ro ...

Learning how to use npm packages in Node.js through tutorials

Seeking tutorials that cover the process of creating a new npm package from start to finish. Interested in topics such as: Necessary folder structure Starting a new package Adding dependencies Understanding the purpose of the bin folder Importance of AMD ...