Resolving promises in a sequential manner can lead to encountering errors along

Currently, I've been attempting to iterate through an array of IDs and pass them into a function (this.handleTransfer) that makes API calls. My goal is for the next iteration to only proceed when a response is received from the previous one. In my quest to achieve this, I turned to Google in search of how promises can help me with this task. However, upon implementing the solution I found online, I encountered the following error after the first iteration:

TypeError: e(...).then is not a function.

The code block responsible for the error was identified as:

return e().then(Array.prototype.concat.bind(t))

This is my current code setup:

const promiseSerial = funcs =>
        funcs.reduce((promise, func) =>
          promise.then(result => func().then(Array.prototype.concat.bind(result))),
          Promise.resolve([]))

        const payments = this.payIDArray;

        const funcs = payments.map(payment => () => this.handleTransfer(payment))

        promiseSerial(funcs)
        .then(console.log.bind(console))
        .catch(console.error.bind(console))

It's worth mentioning that I am utilizing the VueJS framework.

Answer №1

Upon reviewing the sample code provided, I made a few assumptions.

  • Initially, based on your utilization of
    ... promise.then(result => func().then ...
    , it seems that this.handleTransfer(payment) likely returns a function that in turn returns a promise.
  • Secondly, given the use of concatenation in your code, it is assumed that the data returned by your API call is in an array format.

The implementation of promiseSerial presented below generates a promise chain that resolves to the concatenation of arrays received from the this.handleTransfer(payments) calls while maintaining the original sequence of these calls.

const promiseSerial = (funcs) => funcs.reduce((resultPromise, apiPromise) => {
    return resultPromise.then((concatenatedAPIResponses) => {
        const apiCallPromise = apiPromise(); //assuming this.handleTransfer(payment) returns a function  
        //const apiCallPromise = apiPromise; if this.handleTransfer(payment) returns a promise instead of a function

        return apiCallPromise.then((apiCallResponse) => {
            concatenatedAPIResponses = concatenatedAPIResponses.concat(apiCallResponse);
            return concatenatedAPIResponses;
        });
    });
}, Promise.resolve([]));

Check out the Codepen example here

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

Error in Node.js Express: Attempted to access property 'image' of null resulting in an unhandled error event

I've been trying to identify where the issue lies. Can someone lend a hand with this? When attempting to submit the post without an image, instead of receiving a flash message, the following error pops up: and here's the source code link: https: ...

Exiting or returning from a $scope function in AngularJS: a guide

There are times when I need to exit from my $scope function based on a certain condition. I have attempted to achieve this using the return statement. However, my efforts have been in vain as it only exits from the current loop and not from the main scop ...

Dealing with errors in Angular using dependency injection

I'm encountering an issue while attempting to inject $ http to the factory. I received the following error in Angular 1.6: Circular dependency found: $rootScope <- $http <- $exceptionHandler <- $rootScope <- $route Here is what I have b ...

The issues of cross-origin domains arise when utilizing iframes with src links originating from the server side

Encountering a cross-origin domain issue, receiving the following error while working with an iframe: candidateInterviewCtrl.js:39 Uncaught SecurityError: Blocked a frame with origin "http://localhost:9000" from accessing a frame with origin "http://local ...

Organize every rectangle and text element in D3 into distinct groups

Currently, I am working on creating a bar graph using d3.js. The goal is to display text on top of each bar when the user hovers over it. To achieve this, the <text> and <rect> elements need to be grouped inside a <g> element. For Exampl ...

What is the best way to handle a $q.when promise in unit testing?

Currently, I am utilizing $q.when to transform promises from third-party sources, specifically those returned by PouchDB, into Angular promises. Here is the scenario: 'use strict'; angular.module('test', []) .service('pouchdb&a ...

What are the steps to incorporate @svgr/webpack into turbopack within a next.js project?

I'm encountering an issue with turbopack and @svgr/webpack in my project. According to the documentation, they should work together but it's not cooperating. When I run the project without using --turbo (turbopack), everything functions as expec ...

Warning: Unhandled promise rejection - Type error encountered when trying to access property

While working on a simple login validation, I encountered an issue when deliberately inputting an incorrect email in the login post method via postman. UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'password' of null at C:&b ...

Utilizing Bresenham's line drawing algorithm for showcasing box contours

I am seeking a similar behavior to what is demonstrated on , but with some modifications to the boxes: div { display: inline-block; width: 100px; height: 100px; border: 1px solid black; cursor: pointer; } div.selected, div:hover { backgroun ...

Creating identical class names for UL elements underneath LI using JavaScript

In my attempt to dynamically generate the class name within the ul element, I successfully achieved the expected result. The outcome can be viewed in the console of the snippet provided for reference. However, I'm facing a challenge when attempting t ...

Exploring elementary Expressjs query concepts

Just getting started with nodejs and feeling a bit confused. I have a form on my website where users can submit information, and I want to display a response message in an HTML element once the form is submitted. I've been using body parser and Jade v ...

What is the best method for dynamically increasing the data in a shopping cart?

My goal is to stack cart items dynamically every time the addProduct() function is called. I've successfully captured the data, but I'm facing an issue where the quantity always remains at 1 on each function call. Here's the logic I've ...

Creating a dynamic quiz with random images using text boxes in HTML and PHP

I am working on creating a 'guess the picture' style quiz where a random image is displayed as the question, and users must input their answer in a textbox. The question will be selected randomly from 3-5 options each time the page is refreshed o ...

I'm seeking clarification on the composition of Objects in Node.js

After running a console.log on a parameter from the callback function in the Node.js formidable package, here is the output of files: { fileUpload: [ PersistentFile { _events: [Object: null prototype], _eventsCount: 1, _maxListene ...

Bring in resources without specifying

Is there a way to directly import an image into a JSX tag in React without having to declare it at the top of the file using import img from './this/is/file.png'? I attempted to do so with <img src={import './this/is/file.png'} alt= ...

Is there a way to efficiently import multiple Vue plugins in a loop without the need to manually type out each file individually?

I am looking for a way to streamline this code by using a loop to dynamically import all .js files from a specified directory (in this case, the 'plugins' directory). const plugins = ['AlertPlugin', 'AxiosPlugin', 'Confi ...

Continue scanning the expanding page until you reach the end

One of the challenges I am facing is that on my page, when I manually scroll it grows and then allows me to continue scrolling until I reach the bottom. This behavior is similar to a Facebook timeline page. In an attempt to address this issue, I have writ ...

Deletion of a custom function in JavaScript

I have written some basic code to generate and remove an image using functions. Specifically, I need help with removing the image created by the function Generate() when a button linked to the function Reset1() is clicked. Here's the code snippet for ...

Exploring the utilization of type (specifically typescript type) within the @ApiProperty type in Swagger

Currently, I am grappling with a dilemma. In my API documentation, I need to include a 'type' in an @ApiProperty for Swagger. Unfortunately, Swagger seems to be rejecting it and no matter how many websites I scour for solutions, I come up empty-h ...

Looking to eliminate a specific property within an object in MongoDB

I have a BSON document stored in a collection. My goal is to remove a specific key based on a dynamic value. { "_id": ObjectId("53ccff9bbb25567911f208a2"), "image": { "image1": "5213423424234.jpg", "image2": "5213423424235.jpg", "image3": ...