Transferring data from a promise to a variable

Attempting to retrieve a value from a Promise and store it in a local variable within a function resulted in the Promise being resolved last.

The following function, which will be triggered in Vue.js mounted():

getPriceForYesterday(){
    let yesterdayUSD = [];
    for (let i = 0; i < this.cryptos.length; i++) {
        let cryptoName = this.cryptos[i].title;
        let timestamp = new Date(this.cryptos[i].purchaseDate);
        timestamp.setDate(timestamp.getDate() - 1);
        timestamp = timestamp.toISOString();

        let priceYesterday = getPriceForTimestamp(cryptoName, timestamp);
        Promise.all([priceYesterday]).then((values) => {
            console.log("values", values)
            yesterdayUSD.push(values[0]);
        }).catch(e => console.error(e));

    }
    console.log("yesterdayUSD", yesterdayUSD);
    console.log("yesterdayUSD[0]", yesterdayUSD[0]);
}

Result:

yesterdayUSD []
yesterdayUSD[0] undefined
values [13308.06]
values [1278.69]

The goal is to use yesterdayUSD for comparison with a value stored locally and then return the comparison "result" to the vue data.

Answer №1

Perhaps you could modify this function so that it also returns a promise

getPriceForYesterday(){
    return new Promise( resolve => {
        let yesterdayUSD = [];
        for (let i = 0; i < this.cryptos.length; i++) {
            let cryptoName = this.cryptos[i].title;
            let timestamp = new Date(this.cryptos[i].purchaseDate);
            timestamp.setDate(timestamp.getDate() - 1);
            timestamp = timestamp.toISOString();

            let priceYesterday = getPriceForTimestamp(cryptoName, timestamp);
            Promise.all([priceYesterday])
            .then((values) => {
                yesterdayUSD.push(values[0]);
            })
            .then( () => {
                resolve(yesterdayUSD)
            })

        }
    })
}

and then integrate it into the mount() method

mount() {
   ...
   getPriceForYesterday().then( yesterdayUSDArray => {
      //do something with this yesterdayUSDArray
   })
}

Answer №2

The main issue you're facing with retrieving yesterdayUSD is due to the asynchronous nature of promises. They are being executed at different times, causing console.log() statements to not output anything.

To address this, it seems like using Promise.all() could help synchronize the promise resolution process. By creating an array of promises and waiting for all of them to resolve, you can then access the values stored in yesterdayUSD more effectively.

fetchYesterdayPrice(){
    let yesterdayPrices = [];
    let pricePromises = [];

    for (let i = 0; i < this.coins.length; i++) {
        let coinName = this.coins[i].name;
        let timestamp = new Date(this.coins[i].purchaseDate);
        timestamp.setDate(timestamp.getDate() - 1);
        timestamp = timestamp.toISOString();

        let yesterdayPrice = fetchPriceForTimestamp(coinName, timestamp)
            .then((values) => {
                console.log("values", values)
                yesterdayPrices.push(values[0]);
            })
            .catch(e => console.error(e));

        pricePromises.push(yesterdayPrice);
    }

    Promise.all(pricePromises).finally(() => {
        console.log("yesterdayPrices", yesterdayPrices);
        console.log("yesterdayPrices[0]", yesterdayPrices[0]);
    });
}

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

The rendering function of the model is not functioning

I've been struggling to incorporate my blender model into my website using three.js. Despite following various tutorials, I can confirm that the model works fine outside of three.js. If there's something crucial that I'm missing or need to d ...

What is the best way to style the header of a table when scrolling in CSS?

Currently, I am facing an issue with applying the top CSS property to the thead element of a table while scrolling. I have attempted various methods but have been unsuccessful in achieving the desired outcome. Initially, I used the scroll event, however, ...

Locate commas within quotation marks using regex and replace them with their corresponding HTML entity

When dealing with a string like this: "Hello, Tim" Land of the free, and home of the brave I want it to be transformed into: "Hello&#44; Tim" Land of the free, and home of the brave This should be a simple task, but I'm struggling to find th ...

Having trouble making the child process die in NodeJS fork

I'm facing a roadblock here, perhaps it's just a minor issue that I can't seem to solve because of my lack of experience with NodeJS. Currently, I am developing a Bluetooth device that will be controlled by a master application. For prototy ...

PHP: Bootstrap CSS for Carousels

I'm experiencing some difficulties with the Bootstrap CSS Carousel on my website. The left and right arrows seem to be unresponsive, and the slides are not transitioning automatically. I have been unable to identify the root cause of this issue. Belo ...

Mastering the art of utilizing middleware in every HTTP request using Node.js Express

I am currently developing a middleware for my nodejs application and I need to include a header in the request within the middleware before sending it to my index.js endpoint. middleware1.js exports.mw1 = function(req, res, next) { next(); }; middlewa ...

Using JavaScript to display a confirmation dialog box with the content retrieved from a text input field

Can a confirm dialog box be used to show the user-entered value from a form's text box? For instance, if the user enters 100.00, I want the dialog box to say something like, "Confirm Amount. Press OK if $100.00 is accurate." ...

Discover the method for extracting the value from an array that has been transferred from a php script

So here's the situation - I have a text file containing data. The first step is to convert the content of the text file into an array. $lines = file($filename); Next, the data is sent back to the client (the $filename is determined through ajax). ...

Angular and Express: Automatically redirecting to the previous page after user login

A question similar in nature can be found here, although not directly relevant to my situation. Within my Single Page Application, I am implementing PassportJS for user authentication. There are multiple routes that necessitate user login. The routing is ...

What is the process for linking my Next.js application with MongoDB Compass?

Currently, I am working on a project in Next.js called NetMapper where I am developing a web interface for the CLI tool nmap. My main focus right now is creating Sign In/Sign Up forms and storing user information in MongoDB Compass. Despite trying various ...

My function is named, however, the output is recorded prior to the function completing its execution

I've implemented a function named createUser, designed to save user data in the database. If successful, it should return true; otherwise, false. The code for this function is as follows: exports.createUser = (user) => { const salt = crypto.rando ...

issues with jquery functionality on mobile devices

I'm currently working on a website where I've implemented a jQuery script to dynamically load specific parts of an HTML page with an ID of 'guts' into the main content area. The goal was to keep the menu consistent while only changing t ...

struggling with responseText functionality in javascript

I am encountering an issue with passing variables from PHP to JavaScript using JSON. The problem lies in the fact that I am able to debug and view the items in the responseText within my JavaScript, but I am unable to assign them to a variable or properly ...

Problems with ng-repeat in kenwheeler's AngularJS implementation

Hey there! I'm currently using the slick carousel by ken wheeler, but when I implement ng-repeat on the div, it only shows 'listed images'. I'm not sure what I'm doing wrong here. Any ideas? <section class="regular slider" sty ...

Checking the availability of a username by sending an Ajax request every time the user types it may lead to inefficiencies and slower response times. Are there

I have developed a NodeJS authentication application. In this scenario, when a user enters a username, the system will display "username taken" if it is already in use, otherwise it will show "username available". I am interested in understanding the lim ...

Why is the autocomplete minlength and maxheight not functioning properly in MVC?

After entering a value in the text field, data from the database appears but adjusting the height and width of the list box seems to be a challenge. I have set the parameters like minLength: 0, maxItem: 5, but it doesn't seem to make a difference. ...

``There seems to be an issue with the functionality of Passport.js' multiple login system

I'm encountering a strange issue with my login system. Everything seems to be working fine, including local login, Google login, and Facebook login. However, the problem arises when I attempt to register with Google after already registering with Face ...

Encountering a problem when attempting to manually create a featherlight gallery in JavaScript using a list of hrefs: "Error: Unable to call c.first as it

Trying to manually create a featherlight gallery in Javascript by providing a list of hrefs (simple path strings) using: $.featherlightGallery(images); However, I encountered an issue: 'TypeError: c.first is not a function. (In 'c.first()&ap ...

Recent Google algorithm changes impact websites built on AngularJS and JavaScript

Exciting news from Google today (May 28, 2014) - JavaScript content will now be rendered by the Googlebot itself! This means there's no need to worry about serving pre-rendered pages just for crawling purposes. You can find out more details on this an ...

How to use AJAX to retrieve data from a JSON file hosted on an external URL?

Is it possible to extract data from a JSON file that belongs to an external source such as ABS, a company that provides weather information? The weather data is stored in a JSON File. Why am I unable to access this information and save it? & ...