Tips for using a .map() function in conjunction with a promise

I am faced with a challenge where I have an array and for each element in the array, I need to retrieve some data based on that element and then append it to the respective element in the array.

For illustration purposes, I will create a simulated fetch operation using a Promise (in reality, this would involve fetching data from a web service):

let p = new Promise((resolve, reject) => resolve('x'))
let a = ['a', 'b']
a = a.map(x => p.then(y => x + y))
console.log(a)

I expected that when performing the above operation, the first element (a) would invoke the Promise p, and upon resolution, the result would be added to a (resulting in ax). The same process would be repeated for b.

Ultimately, my expectation was to obtain a new array as ['ax', 'bx'].

However, instead of getting the desired outcome, I ended up with an array of Promises.

Given my limited experience with Promises (despite finding them conceptually fascinating), I am struggling to comprehend what might have gone wrong. Can .map() be effectively combined with asynchronous tasks?

Answer №1

I was hoping for a new array ['ax', 'bx'], but instead I ended up with an array of Promises

This is where Promise.all comes into play. Even though it returns a promise for the array, there's no way around it when dealing with asynchronous operations.

const promises = a.map(x => p.then(y => x + y))
Promise.all(promises).then(console.log, console.error)

Answer №2

Update: check out this piece of code that functions exactly as you need it to:

let p = new Promise((resolve, reject) => resolve('x'))
let a = ['a', 'b']
let c =[]
Promise.resolve(a.map(x => p.then(y => c.push(x + y)))).then(() => console.log(c))

Because p.then returns an empty object, your map will result in an array of empty objects.

PS: Feel free to optimize the code. It's getting late where I am, so I'm heading off to bed now.

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

Is there a more efficient method to execute this AJAX request?

$('#request_song').autocomplete({ serviceUrl: '<%= ajax_path("trackName") %>', minChars:1, width: 300, delimiter: /(,|;)\s*/, deferRequestBy: 0, //miliseconds params: { artists: 'Yes' }, onSelect: functi ...

Utilizing ion-slide-box within an ion-content container that allows for scrolling

I've created an Ionic view with the following structure: <ion-content scroll="true"> <ion-list> ... some ion items... <ion-item> <ion-slide-box> <ion-slide ng-repeat="image i ...

Encountering 404 Error in Production with NextJS Dynamic Routes

I'm currently working on a next.js project that includes a dynamic routes page. Rather than fetching projects, I simply import data from a local JSON file. While this setup works well during development, I encounter a 404 error for non-existent pages ...

Unable to Locate Gulp Packages

Whenever I try to run the command gulp in my terminal, my gulp modules are not being found. Surprisingly, all other commands like node -v, gulp -v, and npm -v are working perfectly fine with the latest versions installed. I have tried running these command ...

Interactive image popups with JavaScript

Seeking assistance in generating a popup when selecting an area on an image map using Javascript. As a novice in JS, I have successfully implemented popups for buttons before but encountered issues with this code within the image map - the popup appears br ...

Leveraging the power of async to streamline the serialization of operations with numerous layers of callbacks in Node

I'm relatively new to working with node.js and I'm encountering difficulties in understanding callback functions. The issue arises when I need to execute a series of complex operations that involve a lot of code divided into modules with numerous ...

Obtain a collection of keys that share identical values

In my JavaScript code, I have an array of objects structured like this: objArray = [ {"date":"07/19/2017 12:00:00 AM","count":"1000","code":"K100"}, {"date":"07/21/2017 12:00:00 AM","count":"899","code":"C835"}, {"date":"07/23/2017 12:00:00 AM","cou ...

Unable to Access Browser Page

After printing out the URL in the console, I encountered an issue while trying to retrieve it using browser.get(). The error message displayed is as follows: Failed: Parameter 'url' must be a string, not object. Failed: Parameter 'url&apo ...

Issue with resetting input forms in ReactJS

I have a simple form that seems to be clearing the rest of the fields every time I try to fill it. Additionally, validation errors are being displayed below each field instead of just one. How can this issue be fixed? Here is how the form looks before any ...

What is the best way to use res.sendFile() to serve a file from a separate directory in an Express.js web application?

I have a situation within the controllers folder: //controler.js exports.serve_sitemap = (req, res) => { res.sendFile("../../sitemap.xml"); // or // res.send(__dirname + "./sitemap.xml") // But both options are not working }; ...

Is HTML5 Device Orientation the answer to a dependable compass system?

I am currently developing a project for mobile web that requires access to the compass direction of the user's device. At the moment, my code is quite basic, but here is what I have: var updateDirection = function (evt) { $("#dire ...

Restrict the Angular ng-repeat directive to specific rows only

Suppose we have a JSON dataset listing all languages of books: $scope.data = [{ "title": "Alice in wonderland", "author": "Lewis Carroll", "lang": ["en"] }, { "title": "Journey to the West", "author": "Wu Cheng'en", "lang": [" ...

The Electron BrowserWindow turns dark post execution of the .show() method

Revision: After some tinkering, I discovered that the issue was related to the order in which I created the windows. Previously, my code looked like this: app.whenReady().then(() => { createWindow(); spawnLoadingBlockWindow(); spawnGenerati ...

Tips for customizing a single row in v-data-table? [Vuetify]

My goal is to change the background color of a specific row that contains an entry matching the value of lowestEntry. <v-col cols="8"> <v-data-table :loading="loadEntryTable" loading-text="Searching for data..." ...

What is the technique to make a *ngFor render items in a random order?

I'm working on creating an application that needs to display elements in a random order. However, due to restrictions within the application, I am unable to modify the ngFor directive. How can I achieve displaying ngFor content randomly? ...

Modify the onerror function of the image tag within the onerror function

Here is a way to display images using the img tag: If 1.jpg exists, show 1.jpg. If not, check for 2.jpg and display it if it exists. If neither 1.jpg nor 2.jpg exist, display 3.jpg. <img src="1.jpg" onerror="this.src='2.jpg'; this.oner ...

Utilizing the mobile navigation layout for desktop screens without the need to adjust breakpoints

Having created a responsive site with common breakpoints established in SCSS as mixins, I am now seeking to implement the mobile breakpoint for a single page on desktop view only. Initially, my plan was to create a 'forced-mobile' class by exten ...

Difficulty in accessing controller data in AngularJS with ng-repeat

I am trying to display comments using ng-repeat in a section, but I am having trouble accessing the data. Even after debugging, I cannot access the data without modifying the controller. I am new to Angular and prone to making mistakes. HTML / JS &apo ...

Choosing the open status of an HTML list

Is there a way to determine which containers in a list are currently open and which ones are still closed? Currently, I am utilizing the slideDown(), slideDown(), and addClass functions on divs with the specific class="section_hdl_aktiv". However, I want ...

What steps should I take to show the content on different menu selections?

Check out my full code snippet. <html> <head> <meta charset="utf-8"> <title>Title</title> <link rel="stylesheet" href="https://code.jquery.com/mobile/1.5.0-rc1/jquery.mobile ...