Different option to chained promises

In an attempt to develop a function that acquires a presigned s3 URL (call 1) and performs a PUT request to s3, I find myself contemplating the usage of a nested promise structure, which is commonly recognized as an anti-pattern.

Outlined in JavaScript/pseudocode:

uploadFile(file){
  return new Promise((resolve, reject) => {
    axios.get(getPresignedS3Url).then((url) => { return axios.put(file)}
  })
}

let filePromises = files.forEach(file => uploadFile(file));
Promise.all((filePromises) => notifyUpload(filePromises));

The essential need is to return a promise from the uploadFile function to ensure all promises are resolved. What would be the correct approach to address this situation?

Answer №1

When using axios.get, you are already working with a Promise, so there is no need to wrap it in another Promise using new Promise.

Instead of using forEach which returns undefined, consider using .map to create an array of Promises.

const uploadFile = file => axios.get(url)
    .then((url) => { return axios.put(file); });
Promise.all(
  files.map(uploadFile)
)
  .then(notifyUpload)
  .catch(handleErrors);

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

What is the best way to add data to my collection using the main.js file on the server side in a Meteor application

I am a beginner with Meteor and trying to customize the tutorial codes. I have a code that listens for packets on my server-side main.js. Now, I need to store the data printed on the console into my database collection. import { Meteor } from 'meteor/ ...

Having difficulty transforming shapefiles into geojson

I am in need of JavaScript code that can seamlessly convert shapefile files to geojson and vice versa, but I am struggling to find reliable tools to accomplish this task. After some research, I stumbled upon Calvin Metcalf's repository, which claims ...

The function you are trying to use is not a valid jQuery function

Although I've come across this issue in previous posts, none of the solutions worked for me and it's really frustrating. I'm a newbie to javascript and I'm sure the answer is probably simple. I'm attempting to incorporate the rapt ...

Utilizing PHP to Monitor Devices Sharing the Same Network or IP Address

I am currently working on creating a conversion tracking page with postback in PHP. In order to do this, I need to generate a unique transaction ID for each unique click. One method I am using to track unique clicks is by capturing the user's IP addre ...

The request cannot be completed using GET. The connection has not been established, and the offline queue is not activated

Encountering this unexpected error in the live environment, despite implementing a retry strategy of 500ms and wrapping the setAsync and getAsync functions with a setTimeout of 1s. It's puzzling why this issue persists. Error Message: AbortError at ...

Error: Client was unable to process JSON data

My server setup looks like this: var http = require('http'); //Defining the port to listen to const PORT=8092; //Function that handles requests and sends responses function handleRequest(request, response){ response.statusCode = 200; ...

JavaScript alert causing disruption to Ajax requests

Currently, I am utilizing JQuery Ajax to retrieve a script from the server. $.ajax({ url: src, type: "GET", dataType: "script", timeout: transaction_timeout }).done(function(){}) .fail(function() { alert("Error in server");}) .always(funct ...

What is the best way to develop a unique animation for every v-card?

Is there a way to customize each animation so that it is specific to the selected v-card? Right now, when one card is clicked, all of them play the same animation. data: () => ({ show: true, images: [ {url:require('@/assets/london. ...

JavaScript code that loads a specific DIV element only after the entire webpage has finished loading

How can I ensure that the DIV "image" is loaded only after the entire page has finished loading? What JavaScript code should I use? <div class="row"> <div class="image"> CONTENT </div> </div> I plan to execute the functio ...

Adding an outline to a child mesh in three.js is a simple process

I am interested in adding an outline to meshes. To achieve this, I followed an example that involved creating a new mesh with the same geometry and scaling it. You can find the example here. var outlineMaterial = new THREE.MeshBasicMaterial({ ...

Obtaining the Tinymce Editor Instance using WordPress JavaScript

I am currently in the process of developing a Wordpress plugin that adds a customized metabox below the post editor, including a button. Additionally, the plugin loads a Javascript file just before the closing </body> tag. OBJECTIVE My main goal wi ...

Create a function that binds a select dropdown to each table column header using JavaScript Object Notation (JSON), and then populate an HTML table with the

I have a dynamic table populated with JSON data, and I would like to add a select dropdown for each column. The challenge is that the number of columns is not fixed and they are also populated by JSON. Therefore, I want the select dropdown at the top of ea ...

Creating a dynamic 3D pie chart with Highcharts and JSON data

I am attempting to create a 3D pie chart using HighChart with JSON data. Despite enabling the 3D option, it only displays in 2D. Here is an example of the 3D pie chart I am trying to achieve: https://www.highcharts.com/demo/3d-pie Could someone please he ...

iOS - A clever trick for manually setting focus on an input/textarea

Recently, there have been numerous discussions about the issue in iOS where focusing on an input/textarea element cannot be achieved through manual means. (Check out the threads here and here) It appears that iOS necessitates a genuine tap or click for foc ...

The error message encountered while using String.search("sinh(2"): "Regular expression is invalid."

Encountering an issue: var test = $("#k_w").val().search("sinh("+parseFloat(sinh_array[i])); An error message is displayed by the debugger: Uncaught SyntaxError: Invalid regular expression: /sinh(2/: Unterminated group. sinh_array[i] represents numerica ...

Leverage both props and destructuring in your Typescript + React projects for maximum efficiency!

Is it possible to use both destructuring and props in React? For instance, can I have specific inputs like name and age that are directly accessed through destructuring, while also accessing additional inputs via props? Example The desired outcome would ...

What exactly is the significance of status within Google Chrome?

Today, while using Chrome, I encountered something quite unusual. var foo = ["70036", "70374"] var status = ["70036", "70374"] console.log(status[0]); console.log(foo[0]); One would expect the console to display: 70036 70036 However, the actual output ...

Tips for picking out a particular item from a list of child elements

When I select the first parent's children array, it ends up selecting every other parent's children as well. This is due to index 0 remaining the same for all of them. How can I specify and highlight a specific child? Link: Check out the stackb ...

Unit testing tips: the art of mocking a wrapper function

Unit testing is a new concept for me and I'm currently trying to learn how to stub a wrapper function in Sinon/Mocha. For example, if I have a function like: const user = await User.findOne({ email: email }); I've been successful in stubbing it ...

Eliminating the "as" keywords from the TypeScript code

I'm looking to optimize this TypeScript code by removing the unnecessary as keywords. The code includes a method called update where I'm attempting to improve the organization of sanitizing, validating, and attributing data. However, it seems tha ...