Exploring an array using bluebird promises

I am currently facing an issue where I need to iterate over an array containing promises. My goal is to multiply all the values in the array by 2 and then return the updated array:


var Bluebird = Promise.noConflict();
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

function processArray(arr) {
    return Bluebird.each(arr, function(value) {
        return value = value * 2;
    }).then(function(updatedArr) {
        console.log('--done--');
        console.log(updatedArr);
        // should return [2, 4, 6, 8, 10, 12, 14, 16, 18];
    });
}

processArray(arr);

However, my function seems to be returning the original array instead of the updated one. Can someone please assist me with this? Here's a link to my fiddle for reference:

http://jsfiddle.net/mpo4yrmu/71/

Thank you in advance!

Answer №1

Recommendation: Replace the usage of .each with .map.

While .each does not pay attention to the return value, .map certainly does.

Code Playground: http://jsfiddle.net/free_soul/mpo4yrmu/73/

var Bluebird = Promise.noConflict()
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

function loopThroughArray(arr) {
  return Bluebird.map(arr, function(value) {
    return value = value * 2;
  }).then(function(arr) {
    console.log('--done--');
    console.log(arr);
    // Expected output: [2, 4, 6, 8, 10, 12, 14, 18, 19];
  });
}

loopThroughArray(arr);

Answer №2

let PromiseFree = Promise.noConflict()
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];

function iterateOverArray(numbers) {
    return PromiseFree.map(numbers, function(num) {
        return num = num * 2;
    }).then(function(result) {
        console.log('--completed--');
        console.log(result);
        // expected output: [2, 4, 6, 8, 10, 12, 14, 16, 18];
    });
}

iterateOverArray(numbers);

Make use of .map method to reach your objective as demonstrated above.

Why would using .each not be suitable in this scenario?

Response: The each function operates as an iterator, iterating over an array or an array of promises, whereas the map function also iterates over an array but it waits for the values returned from each iteration and stores those return values in an array, which can be accessed in the subsequent then block.

Answer №3

Bluebird.each() keeps the original array unchanged, hence why the initial array is being printed.

Bluebird.each

...Maintains the original array as is; this function is designed for side effects. If the iterator function produces a promise or a thenable, the resolution of that promise is awaited before moving on to the next iteration.

http://bluebirdjs.com/docs/api/promise.each.html

The recommended approach would be to utilize Javascript's built-in Array.prototype.map():

//Example using promises
...function(arr) {
    console.log('done!');
    console.log(arr.map(function(element) {
      return element * 2;
    }));
   }

Answer №4

the result you are receiving is not a direct reference value. You can achieve it in a similar manner, but keep in mind that the values of the array will be modified.

var Bluebird = Promise.noConflict()
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

function iterateOverArray(arr) {
     Bluebird.each(arr, function(value, i) {
     arr[i] = arr[i] * 2;
  }).then(function(arr) {
    console.log('--completed--');
    console.log(arr);
    // expected output: [2, 4, 6, 8, 10, 12, 14, 18, 19];
  });
}

iterateOverArray(arr);

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

Vue: Struggling to render JavaScript Map containing keys and values using v-for :key

I have an example Json data like so: { "data":{ "1":{ "color":"red", "size":"big" }, "2":{ "color":"red", "size":"big" }, "3":{ "color":"red", "size":"big" }, ...

How is it possible that the SetTimeout code continues to run even after calling clearTimeout

I have this code snippet within my react component: //some code var timeout = null; //global variable //some more code useEffect(() => { if(...some condition) { console.log('test1'); timeout = setTimeout(() => { ...

How can I retrieve the decimal x and y coordinates when the mouse is moved in Typescript Angular?

I am in the process of transitioning my user interface from Flash/Flex, where it stores values in decimal format. I need to access and reuse these values. Here is a demo showcasing my problem. Here is a snippet: import { Component, Input } from '@an ...

Hiding a column in jQuery DataTables

Can the jquery datatables plugin be used to easily hide and show a table column? I've successfully refreshed the table data by using fnClearTable and fnAddData. However, I'm facing a challenge in one of my table views where I need to hide certa ...

Obtain asynchronous result from updating state in React

I am trying to achieve the following: myFunction = () => { this.setState( state => { const originalBar = state.bar; return { foo: "bar" }; }, () => ({ originalBar, newBar: state.foo }) //return this object ...

Controlling Javascript events

Currently, I am working on implementing an in-place editor using jQuery. The functionality is such that when you click on the text you wish to edit, it will replace the content with an input field, specifically a select tag. Everything seems to be functio ...

Discover the location following a designated distance along a direct path connecting two points in the Google Maps API

Using the Google Maps API, I have plotted a straight line from point P1 to point P2. Both points have latitude and longitude coordinates available. I am interested in finding a point (P) along this straight line, located at a specific distance from P1. F ...

AngularJS utilizes JSON objects to store and manipulate data within

My task requires accessing information from an array that is nested inside another array in Json format. Here's a more detailed example: [ { "id": 1, "name": "PowerRanger", "description": "BLUE", "connections": [ {"id": 123,"meg ...

I am experiencing a JSON parse error while making an AJAX request after upgrading to Codeigniter 3.x. What could be the reason behind this

I am currently in the process of updating my Codeigniter framework from version 2.2.6 to 3.0.6, and unfortunately, this update has caused some previously working code to break. One specific error that I am encountering is "SyntaxError: JSON.parse: unexpect ...

Encountering Vue linting errors related to the defineEmits function

I am encountering an issue with the linting of my Vue SPA. I am using the defineEmits function from the script setup syntactic sugar (https://v3.vuejs.org/api/sfc-script-setup.html). The error messages are perplexing, and I am seeking assistance on how to ...

What is the method for linking images to URLs in my carousel?

I am in the process of revamping a confluence page that showcases a variety of visualizations. Here is the code snippet I am currently working with: <div class="carousel"> <img src="image1.jpg"> <img src="i ...

Tips for including parameters in an array of values when using getStaticPaths

I'm trying to retrieve the slug value that corresponds with each number in the getStaticPaths for my page structure: /read/[slug]/[number]. The code I have is as follows: export async function getStaticPaths() { const slugs = await client.fetch( ...

The functionality does not seem to be functioning in Mozilla Firefox, however it is working correctly in Chrome when the following code is executed: `$('input[data-type="choise"

I am currently working on an online test portal and everything is functioning properly with Chrome. However, I am encountering an issue with Mozilla Firefox. My code works fine in Chrome but not in Mozilla Firefox. Please suggest an alternative solution to ...

rearrangement of characters in a string (javascript)

I am currently working on a game where users have to guess a word by selecting the right symbol from the alphabet. When the user guesses correctly, the code is supposed to replace all placeholders with the correct character, but in the wrong order. var se ...

Save your AngularJS SVG file as a JPG

I am attempting to develop a custom directive that will allow me to convert an SVG file into a JPG or PNG format. I stumbled upon this website: http://bl.ocks.org/mbostock/6466603 So, I decided to try and implement something similar with the following co ...

Syntax error is not caught - why are there invalid regular expression flags being used?

I'm attempting to dynamically create rows that, when clicked, load a view for the associated row. Check out my javascript and jquery code below: var newRow = $('<tr />'); var url = '@Url.Action("Get", "myController", new ...

The propagation of SVG events from embedded images via the <image> elements

I'm currently developing a diagramming tool using HTML, CSS, and Javascript with SVG for the drawing canvas. This tool consists of predefined "building blocks" that users can place on the canvas, rather than allowing free-hand drawing of shapes. Each ...

What is the best way to obtain the output of a JavaScript function on the server side?

I'm dealing with a JavaScript function that returns an array in this particular format: <script type="text/javascript"> function looping() { var column_num = 1; var array = []; $("#columns ul").not(" ...

How can I customize the appearance of the container and items in a dropdown <select> menu?

Im using contact form 7 on wordpress, i don't want to use a plugin rather use plain css/js to bring the results if possible. Something like this : https://i.stack.imgur.com/VTWRg.jpg ...

Encountering a glitch when utilizing framer-motion's Animated Presence feature

I am working on a React slider where new data replaces old data whenever the user clicks on the Next or Previous button. To enhance the slider with beautiful animations, I decided to use framer motion. The animations are almost perfect, but for some reason ...