Connecting promises to build upon past outcomes

Can someone help me figure out how to access previous results in promises? I've been following the guidance on this stackoverflow thread.

I had success with 2 promises, but things got tricky when I added a 3rd promise that makes a POST request to an API. The result ended up being the post request itself instead of the response from the request.

My app's workflow involves inserting an item into a DB first. Then, using the insertId, I have to add multiple 'children' items into the database. Additionally, these values must be sent to an API which will return another ID to associate with the initial insertId. Here is a simplified version of my code:

let name = req.body.name;
let value = req.body.values;
let obj = {name:name};
let entries = [];
let a = db.items.insertItem(name);

let b = a.then((data) => {
    let insertId = data.insertId;
    let promises = [];
    values.forEach((val) => {
           entries.push({value:val)})
           promises.push( db.values.insertValuesForItem(insertId,val));
    })
    obj.entries = entries; 
    return promises;

})
let c =  b.then((data) => {
     return request.post(constants.devUrl,
    {
        headers:{
        'Authorization': 'bearer ' + constants.developerToken,
        'content-type': 'application/json'
        },
        json:obj
    });
});

Promise.all([a,b,c]).then(([resa,resb,resc]) => {
   //resc here contains the post request info e.g the post data and headers
   // what I really want from resc is the response from my post request
    res.redirect(200,'/items/' +  resa.insertId);
})

However, I need the actual response from the API request in resc, not just details about the request itself. Any suggestions on how to achieve this?

Answer №1

After the question was reopened, I want to re-emphasize what I mentioned in the comments:

Your code has two issues:

  1. Mistake in chaining promises:

    let b = a.then((data) => {
        let insertId = data.insertId;
        let promises = [];
        values.forEach((val) => {
               entries.push({value:val)})
               promises.push( db.values.insertValuesForItem(insertId,val));
        })
        obj.entries = entries; 
        return promises; // this variable is accessed later as `data`, but
                         // never actually used => it's pointless
    
    })
    

    By returning promises, you are actually returning a Promise that will only provide your array of promises when fulfilled. This leads to:

    1. In the success callback of b, you receive data (which is an array of promises) but don't utilize it.
    2. In
      Promise.all([a,b,c]).then(([resa,resb,resc])
      , resb represents the array of promises, not the results of the db operation.

    I understand the intention to synchronize execution, but this isn't the right method.

  2. Wrong assumption about request.post returning a promise:

    let c =  b.then((data) => {
         return request.post(constants.devUrl,
        {
            headers:{
            'Authorization': 'bearer ' + constants.developerToken,
            'content-type': 'application/json'
            },
            json:obj
        });
    });
    

    As noted in the comments, you're utilizing this requests library. Therefore, in this scenario, c indeed represents a Promise, but its result isn't the expected httpResponse.

    • If you wish for requests to return promises, you should select one of these variations of the requests library that offer promise support.

    • However, if you prefer not to switch libraries, you can synchronize execution by also assigning a callback function for the post method. For instance:

      var gotResponseCallBack = function(err, httpResponse, body){
          return httpResponse;
      }
      request.post(constants.devUrl,
      {
          headers:{
          'Authorization': 'bearer ' + constants.developerToken,
          'content-type': 'application/json'
          },
          json:obj
      }, gotResponseCallBack); 
      

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

difficulties retrieving information with $http.jsonp

Here is the code snippet that I am working with: var url = 'http://someURL?arg1=test&arg2=test&callback=JSON_CALLBACK'; $http.jsonp(url) .success(function(data){ console.log(data.found); }); Despite receiving a status code of 200 o ...

What is the best way to connect the elements in two separate arrays?

I have a scenario with two arrays and a variable: var Names = ['jack', 'peter', 'jack', 'john']; var Ids = ['1' , '2' , '3' , '4' ]; Also, I have this search varia ...

Newbie in JavaScript - reinitiating my for loop journey

After running an animation in 4 steps, I want it to restart once all the steps are completed. var aSteps = [ { "x": "800", "y": "0" }, { "x": "800", "y": "500" }, { "x": "0", "y": "500" ...

Verify the Javascript for file upload in ASP.NET folder prior to uploading it

Struggling with this problem for days now, I could really use some fresh perspective. My setup includes Windows Server 2012, IIS 8.0, and ASP.NET 4.5. I'm new to both IIS and ASP.NET, so please bear with me. The website I'm working on involves f ...

An issue occurred with lodash during the construction of /@types/lodash/common/object.d.ts at line 1188, character 142: Expected '('

Things were going smoothly, but out of nowhere my build started failing. Here are the errors that are popping up: ERROR in /node_modules/@types/lodash/common/function.d.ts (852,68): ';' expected. ERROR in /node_modules/@types/lodash/common/commo ...

Automate Zoom join function with the help of puppeteer

Having trouble joining a Zoom meeting using Puppeteer, my code is not capturing the password field. Can anyone assist? Here is my code snippet: const puppeteer = require("puppeteer-extra"); const StealthPlugin = require("puppeteer-extra-plu ...

Stylus Vue Vite: The Trio of Global Variables

I'm trying to figure out how to globally import and use stylus variables in my Vue Vite project. How can I achieve this and access the variables within the script section of my Single File Component (SFC)? Below is an excerpt from my Vite config: exp ...

When representing audio as sound bars on a canvas, the previous drawing is retained if canvas height is not specified

After obtaining an audioBuffer containing an audio clip, I proceed to create a visualization by drawing a series of sound bars in the shape of a circle: const { audioContext, analyser } = this.getAudioContext(); const source = audioContext.createBufferSou ...

Repeating the setTimeout function in a loop

I've been delving into JavaScript and trying to understand it better. What I'm aiming for is to have text displayed on the screen followed by a countdown sequence, like this: "Test" [1 second pause] "1" [1 second pause] "2" [1 second pause ...

Develop a cross-platform application using webpack for both web browsers and Node.js

I'm currently developing my first module, and the code is almost identical for both browser and node.js versions. The only variance lies in the use of XmlHttpRequest for the browser and the http module for node.js. Here's a sample code snippet t ...

What is the process for importing a PLY mesh containing triangles and individual vertices into Three.js?

I am trying to showcase a model in Three.js that includes triangles and isolated vertices. The model is encoded in a PLY format. I am using THREE.Mesh to display the triangles and THREE.Points to show the isolated vertices, using the same geometry object f ...

Attempting to automate the process of clicking a button on a webpage using cefsharp

Hello, I am currently working with cefsharp and vb.net to develop a code that will help me navigate to the next page of a specific website. The website link is: https://www.recommendedagencies.com/search#{} My goal is to extract the list of company names ...

Using $watchGroup to monitor changes in an array and automatically updating it

Issue: I am facing a challenge where I want to pass an array of variables into $watchGroup and iterate through the array to update the values of each element. However, the current approach I am using does not seem to be effective: $scope.secondsElapsed = ...

Fluctuating updated site (ajax)

What method do you recommend for maintaining the data in a table on a page current? Currently, I am using a timer that connects to the server via ajax every 2 seconds to check for updates. Is there a way to trigger an event or function only when the cont ...

Building a dynamic tab menu using JavaScript: A step-by-step guide

In order to generate dynamic tab menus with JavaScript, I am seeking a solution that does not rely on jQuery as it may not be supported by all mobile devices. Any advice for replicating the same functionality using pure JavaScript would be greatly apprec ...

Trigger a function when <a> is clicked, which will then increment the count by one and reflect this change in the database

The database generates the content of this div ordered by a count number called "cts". Whenever I click on the div, I want the "cts" number to increase by one, and then update the change in the database. This will result in the content changing accordingly ...

JavaScript causing values to disappear when the page refreshes

When a user hovers over ImageButtons, I use Javascript to change the ImageUrl. However, on submitting the form, the updated ImageUrl property is not reflected in the code behind. Similarly, I also dynamically update a span tag using Javascript, but its alt ...

Leveraging the ReactJS Hook useState for detecting Key press events

As I am in the process of constructing a piano, I want it to showcase certain CSS styles when the user "presses" specific keyboard buttons (via keydown event) - even enabling the simultaneous clicking of multiple different buttons. Once the user releases t ...

Debugging Typescript code with line numbers

When opening the console in a browser, typically the javascript line number of a function call or error message is displayed. However, my current setup involves using TypeScript, which gets compiled to Javascript. I am wondering if there is a way to retr ...

React.js "universal" component that is able to be generated multiple instances of

I'm struggling to fully understand this problem. Here's the issue: imagine there is an app where I need to generate notifications, dialogs, or other similar elements from my code. One option is to have a "global" component that controls everyth ...