Tips on passing a variable and API response to the following promise in JavaScript!

Using the initial promise "crypto.model.find()" allows me to store an array of "symbols" ( symbol[] ) from the database and retrieve some IDs that I will utilize to construct a URL for making a request to an API using axios.get(url).

Upon receiving a response from the API in the second promise, it appears that I lose access to my symbol[] array.

At this point, I require both the API data and the symbol[] array, but I am unsure about how to achieve this.

I have come across suggestions of returning an array and passing it along the chain of promises, however, in this particular scenario, it seems challenging to implement such an approach like so: return [axios.get(url), symbol[]]

// Retrieving coin descriptions from DB using Mongoose
cryptoModel.find()
.then(docsCrypto => {
        let coingeckoIDsRequest = '';
        let symbol = [];

// Iterating through the DB response
        docsCrypto.forEach((eachCrypto) => {
// Building the symbol array based on DB values
            symbol.push(eachCrypto.symbol)
// Creating a portion of the HTTPS API URL request with the DB IDs
            coingeckoIDsRequest += eachCrypto.coingecko_id + '%2C'
        })

// Constructing the URL
        let url = 'https://api.coingecko.com/api/v3/coins/markets?vs_currency=eur&ids=' +
            coingeckoIDsRequest.substr(0, coingeckoIDsRequest.length-3) +
            '&order=market_cap_desc&per_page=100&page=1&sparkline=false&price_change_percentage=24h%2C7d%2C30d%2C200d'

// Returning the API data
        return axios.get(url)
})
// !!! >>>>  My goal is to proceed to the next line with both the API data AND the symbol[] array
.then(res => console.log(res))
// Log error if any  
.catch(err => console.log(err))

Answer №1

To consolidate the two elements you want to pass on, simply utilize the Promise.all() method. The type difference between a Promise and an Array is inconsequential in this case.

Efficiently employ Array.prototype.map() to streamline the process.

cryptoModel.find()
.then(docsCrypto => {
    let symbols = docsCrypto.map(eachCrypto => eachCrypto.symbol);
    let url = 'https://api.coingecko.com/api/v3/coins/markets?vs_currency=eur&ids=' +
        docsCrypto.map(eachCrypto => eachCrypto.coingecko_id).join('%2C') +
        '&order=market_cap_desc&per_page=100&page=1&sparkline=false&price_change_percentage=24h%2C7d%2C30d%2C200d';
    return Promise.all([axios.get(url), symbols]);
})

In the subsequent steps of the sequence, leverage destructuring for easy access to the dual outputs.

.then(([axiosResult, symbols]) => {
    console.log(axiosResult);
    console.log(symbols);
});

Answer №2

Consider moving the symbol array declaration outside of the find function for better efficiency.

Answer №3

To immediately resolve a promise with the value of a variable, you can utilize Promise.resolve(your_variable).

Afterwards, you can merge these promises using Promise.all.

In this specific scenario, I have opted to use setTimeout instead of the actual axios function.

let variable = "value of a variable";

const axios = {
  get: () => new Promise(
    res => setTimeout(() => res('axios response'), 1000)
  )
}

Promise.all([
  axios.get(),
  Promise.resolve(variable)
]).then(
  resolved => console.log(resolved)
);

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 guide on how to insert content into a text area using a drop-down menu choice

I'm a total beginner at this. Is it possible to use JavaScript to automatically fill in a text area on an HTML form based on what is selected in a drop-down menu? If so, can someone please explain how to achieve this? ...

The error message appeared as a result of the bluebird and mongoose combination: TypeError: .create(...).then(...).nodeify is

Recently, I encountered an issue while attempting to integrate bluebird with mongoose. Here's the scenario: I wrote some test code using bluebird without incorporating mongoose, and it worked perfectly. The code looked something like this: A().then( ...

Demonstration of Concurrent Page Processing in Flask

Currently, I am working on an application that heavily utilizes graphics using libraries such as Raphael and graphdracula. The main functionality of the application involves drawing various graphs across different pages named graph1, graph2, and graph3. L ...

The jQuery click and load function are failing to function as expected

Currently, I am facing an issue while trying to load text from a txt document into a div using the following code: $(document).ready(function(){ $('button').click(function(){ $('#contenthere').load('Load.txt'); ...

Console displaying a 400 bad request error for an HTTP PUT request

I'm currently in the process of developing a react CRUD application using Strapi as the REST API. Everything is working smoothly with the GET, DELETE, and CREATE requests, but I encounter a 400 bad request error when attempting to make a PUT request. ...

Error encountered in jQuery validation: Uncaught TypeError - $(...) ""valid is not a function" is displayed with proper references and order

When I try to call a function, I keep getting an error message that says "Uncaught TypeError: $(...).valid is not a function"... JS $('input[data-val=true]').on('blur', function() { $(this).valid(); }); HTML <div class="col-x ...

Broadcasting Packets Between Node.js Ports

I have a set of server.js and client.js scripts that work in tandem. Below is the server.js script... var express = require('express'); var appMain = express(); var appReset = express(); var serverMain = require('http').Server(appMain ...

Redux repeatedly triggers re-rendering despite the absence of any changes in the state

This is my first venture into React-Redux projects. I was under the impression that React only re-renders when a component's state changes. However, I am currently facing confusion. The component is being re-rendered every 1 to 3 seconds even thoug ...

What is the best way to implement CSS in this JavaScript Fetch code in order to manipulate the text's position and font style

Hello, I am just starting out with JS. Is there a way for me to customize the position and font of text in this JS Fetch function using CSS? Any help will be greatly appreciated. let file = 'art.txt'; const handleFetch = () => { fe ...

Issue observed: React Map layer is not loading until mouseEnter event happens

The map is displayed with the color fill only when a mouse enter event occurs. How can I make it trigger on load instead? I am working with react-simple-maps, and the JSON data is successfully loading the map on mouse enter. You can find the source code ...

Variable unique to the specific function in universal function

Can you explain why the alert displays "AAA" instead of "BBB"? http://jsfiddle.net/Lp4cS/ var z = "AAA"; function xx() { var z = "BBB"; yy(); } function yy() { alert(z); } xx(); ...

Utilizing JavaScript to iterate through objects retrieved via Ajax calls

Recently, I've been diving into the world of Javascript and delving deep into AJAX. Utilizing Vanilla JS along with simple AJAX, my current task involves fetching a user object from a URL based on the user's input ID. Despite attempting to use .d ...

What is causing the digest loop from this angular filter grouping?

My goal is to showcase a variety of items in batches of N at a time. The reason for chunking the items is because I need them to be laid out in a tabular or gridded format (each group of N items forms a row, with each item being a column). Below is my atte ...

Error in node.js framework due to memory allocation issue

Hello, I'm encountering an issue while running my JavaScript program. I keep getting a memory error. Can anyone help me identify the exact problem? <--- Last few GCs ---> [12908:0000015EB93DE800] 29162 ms: Mark-sweep 1396.7 (1425.2) -> 1 ...

Tips for incorporating the "define" function into your Mocha testing

Starting my journey with JavaScript testing, I made the decision to use Mocha. The specific modules I am looking to test are AMD/RequireJS. However, it appears that Mocha only works with CommonJS modules. Consequently, when trying to run it, I encounter t ...

Retrieve the URL of an image located within an <li> tag within a jQuery selector item array

I am currently using a jQuery slider plugin to display images, and I am attempting to retrieve the URL of the current image when a button is clicked. The slider functions by showcasing all the image slides as list items in a continuous horizontal row. It ...

Tips on incorporating personalized javascript functions into Durandal

I am currently working on my first project using the Durandal framework to create a basic website. I have encountered an issue while trying to incorporate a simple JavaScript function. My goal is to execute the function after the DOM has loaded, but I am u ...

Is there a method to bypass the need for app.get() for each static file in express?

As I delve into using express.js, I'm faced with the task of serving numerous static files from my server - whether it's a .css, .jpg, .svg, .js, or any other file type. Is there a way to accomplish this without having to manually use app.get() f ...

An issue occurred during the construction of an angular project: The Tuple type '[]' with a length of '0' does not contain any elements at index '0'

When I run the command ng build --prod, I encounter the following error: ERROR in src/app/inventory/inv-parts-main-table/dialog-component/dialog-component.component.html(5,16): Tuple type '[]' of length '0' has no element at index &apo ...

jQuery does not have the capability to automatically calculate Value Added Tax on form submissions

I have included this section in my form to calculate the value added tax (VAT): <div class="col-md-4"> <div class="form-check"> <input type="radio" id="vat_on" name="vat" value=&q ...