Trapped by commitments

I am currently working with an array of projects and an array of dates. My goal is to map the dates to the projects and make API calls to retrieve report URLs. I am trying to collect an array of objects that contain the URLs and the corresponding name-date of the projects, if the data exists and I receive the URL. However, my current code is only returning an array of objects with promises...

  const getURL = async url => {
    try {
      await fetch(url, {method: 'GET', headers: headers_data})
        .then(response => response.json())
        .then(data => data.urls[0]);
    } catch (error) {
      console.log('Error getting links', error);
    }
  };
 let linksToDownload = [];
 await Promise.all(dateOfReport.map(async (date) => {
     await Promise.all(apps.map(async (appId) => {
      const API = process.env.API + appId + "&date=" + date ;
      let url = getURL(API)
      let obj = {
        name: date + "appId" + appId,
        value: url,
      }
      return linksToDownload.push(obj);
    }));
    return;
  }));

  console.log(linksToDownload);

Currently, my log displays:

[
  { name: '2020-04-29appIdda555', value: Promise { <pending> } },
  { name: '2020-04-29appIdqqq444', value: Promise { <pending> } },
  { name: '2020-04-30appIdda555', value: Promise { <pending> } },
  { name: '2020-04-30appIdqqq444', value: Promise { <pending> } }
]

I appreciate any help in resolving this issue. Thank you.

Answer №1

Make sure to add an await in

let url = getData(API);

– it should be

let url = await getData(API);

You might want to restructure things like this:

// Function to fetch JSON from a URL asynchronously.
async function getJSON(url) {
  const resp = await fetch(url, { method: "GET", headers: headers_data });
  const data = await response.json();
  return data;
}

// Retrieve the first report URL for a specific app ID and date.
// NOTE: error handling needs to be implemented
async function getReportURL(appId, date) {
  const apiUrl = process.env.API + appId + "&date=" + date;
  const data = await getJSON(apiUrl);
  const url = data.urls[0];
  return {
    name: date + "appId" + appId,
    value: url,
  };
}

// Loop through date and app arrays to create an array of promises...
const linkPromises = [];
dateOfReport.forEach(date => {
  apps.forEach(appId => {
    // NB: no 'await' used here, allowing requests to run in parallel.
    linkPromises.push(getReportURL(appId, date));
  });
});

// Await all promises to receive the final outcome.
const links = await Promise.all(linkPromises);

console.log(links);

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

A Bluebird promise was generated within a NodeJS handler function, however it was not properly returned from the function

Below is the nodejs code for an express middleware function: Middleware.is_authenticated = function(req, res, next) { if(req.system_session == undefined || req.system_session.login_status == false) return res.status(401).send({errors: true, error: &ap ...

Unable to activate primary error handler in my Node.js Express application

I have implemented node express (4.15.2) and used the default error handler provided by the express generator function to manage errors. Here is the code snippet: const app = express(); app.set('port', config.enviroment.portNumber); app.use(log ...

Ensure the browser back button navigates to the login page seamlessly, without displaying any error

A scenario I am working on involves a Login jsp that accepts a user email and sends it to a servlet. If the provided email is not found in the database, the servlet redirects back to Login.jsp with an attribute "error". Within the header of Login.jsp, ther ...

Angular2 Dropdown not updating with values from API

Here is the structure of my project flow: import_product.html <div class="row custom_row"> <div class="col-md-2">Additional Duty: </div> <div class="col-md-2"> < ...

Issue encountered with edges helper and a partly opaque object rendering

My goal is to create a realistic earth using three.js, similar to this example, which is an improvement from this one. However, I am facing an issue where the rendering order of the sky, earth, and atmosphere is not being properly interpreted by the render ...

The absence of FormData.entries in submit is a limitation of the Vue framework

I recently created a Vue-App that consists of a simple form with just one <input name"surname"> and a <button type="submit">. The use case is to input "myname" and submit the form. However, when I initialize new FormData( ...

Switch between hiding and showing the DIV element flaw

I am currently working on a piece of code that involves simple HTML and JS to show/hide elements. Here is the code snippet: // Enabling forEach for 'querySelectorAll' and 'getElementsByClassName' HTMLCollection.prototype.forEach = No ...

Preventing multiple users from saving the same value for a field using ajax and C#: Best Practices

On my aspx page, I am collecting email addresses from users and making an ajax call like so: function CheckEmailExistence() { $.ajax({ url: "Handler.ashx", contentType: "application/json; charset=utf ...

Modify the color of CSS for all elements except those contained within a specific parent using jQuery

I have a color picker that triggers the following jQuery script: //event.color.toHex() = hex color code $('#iframe-screen').contents().find('body a').css('color', event.color.toHex()); This script will change the color of al ...

Tips for incorporating animation when opening a Jquery SimpleModal

The SimpleModal website features an animation-enabled example with the following sequence: 1. Display modal only 2. Fade in the overlay The code snippet for this animation is as follows: $("#the-div").modal({ onOpen: function (dialog) { dialog.overl ...

Having issues with Sequelize and SQLite auto increment functionality. No errors when using AutoIncrement, but the auto increment feature is not working. On the other hand, errors arise when using

I am currently in the process of developing a discord bot, which includes 2 slash commands. One command is called /setup, used for adding the guildId and an adminChannel to a database. The other command is named /onduty, which is used for adding the user, ...

Display all event date markers, even if some dates are missing

Using the FullCalendar plugin has been a great experience for me. I have managed to successfully read data from a JSON object with the following code: function press1() { var employees = { events: [] }; ...

Jquery Deferred failing to activate done or when functions

I'm currently working with 2 ajax calls that I'm connecting using $.when in order to execute certain tasks once they are completed. Below is the code snippet: function ajaxCall(url, targetDiv) { dfd = new $.Deferred(); $.ajax({ ...

Using HTML and JavaScript, we can set two different color values - one for the background and one for the h1 title

I am trying to save two values, one for the h1 tag and one for the body background. I want the user to select color 1 and color 2. When I press the third button, all changes should be applied and the colors should change. I have attempted this but with no ...

overlay appears as I reveal the slide-out menu

Struggling with adding an overlay to an expanding navigation bar, similar to Youtube's overlay when the slide-out nav is open. Need help with the implementation. Here is the javascript code for the expanding navigation using jQuery: 'use strict ...

Manipulating object information within a nested for loop

I have a variable called jobs in my scope, which is an array containing objects for each department along with their respective data. [ “Accounting”: { “foo” : “foo”, “bar” : "bar" }, “Delivery”: { ...

Having issues with @react-three/drei in next.js environment

Having trouble using drei materials and other features like MeshWobbleMaterial, MeshDistortMaterial, or ContactShadows? You may encounter errors such as: react-three-fiber.esm.js:1383 Uncaught TypeError: Cannot read property 'getState' of null a ...

Guide to creating dynamic borders around your PHPexcel output

Looking for assistance on adding borders around output arrays in an Excel report using PHPexcel. I reviewed the documentation, but the examples are static, requiring a predefined number to set. My goal is to have all arrays transferred to Excel with bord ...

What is the reason behind getComputedStyle having visibility set to visible?

What is the reason behind getComputedStyle always returning element visibility as visible even when no explicit visibility has been set? For instance: getComputedStyle($('#block1')[0],null).visibility; --- "visible" Meanwhile: $('#block1&a ...

What is the reason behind classList returning 'undefined' unless getElementById is explicitly used?

Why is it that I can't seem to select multiple elements with the same class (using querySelector, querySelectorAll, getElementsByClassName, etc) and use classList to check if just one div contains a specific class? I've come across tutorials tha ...