Ways to extract repeated value from a function?

Currently, I am working with two files. One file contains a script that generates a token, while the other file handles that token.

The issue arises with the second script, as it only logs the initial token received and does not update with any new values.

This is how I am managing the token:

const first_file = require("./first_file.js");
first_file.first_file().then((res) => {
    console.log(res);
});

Obviously, this approach will not suffice because it does not reflect the updated value of the token.

first_file = async () => {
    return new Promise(async (resolve, reject) => {
        //Generating the token
        (async () => {
            while (true) {
                console.log("Resolving...");
                resolve(token);
                await sleep(5000);
                resolved_token = token;
            }
        })();
    });
};

module.exports = { first_file };

In an attempt to continuously resolve the token, I implemented a while..loop. However, this method proved unsuccessful. Is there a more efficient way to directly export the variable for easier execution?

Answer №1

It seems like you are looking to handle promises in JavaScript, but there is a misunderstanding about how promises work.

You cannot resolve a promise multiple times, as it goes against the nature of promises in JavaScript.

Generator Function

However, you can use a generator function to generate new values from a function. This type of function, also known as a generator, allows a function to reenter its context and yield results using the yield keyword, similar to async/await.

Generators are often used in loops like for..of and have a next() method to yield the next value.

For example:

const delay = ms => new Promise(res => setTimeout(res.bind(null, ms), ms));

async function* generator() {
    yield 'yield result from generator!'
    for (let ms = 100; ms <= 300; ms += 100) {
        yield 'delay: ' + await delay(ms) + ' ms';
    }
    yield delay(1000).then(() => 'you can also yield a promise!');
}

async function main() {
    const gen = generator();
    console.log('1st', (await gen.next()).value);
    for await (const ms of gen) {
        console.log(ms)
    }
}

main()

The * after the function indicates that it is a generator. When combined with the async keyword, it becomes an Async Generator.

Generators are versatile and useful for generating values on demand, passing data like a pipe, or returning endless values from a function.

Callback Approach

Another approach is the callback method, commonly used in older Node.js versions, where a callback function is passed as an argument.

Example:

const delay = ms => new Promise(res => setTimeout(res.bind(null, ms), ms));

async function callback(fn) {
    fn('yield result from callback!');
    for (let ms = 100; ms <= 300; ms += 100) {
        fn('delay: ' + await delay(ms) + ' ms');
    }
    await delay(1000);
    fn('yield asynchronously!');
}

callback(value => console.log(value));

Although the callback approach is functional, it can lead to issues such as creating function scope problems, disrupting control flow, and lacking a break keyword. It may not be the most recommended method for handling asynchronous operations.

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

Unable to save and subsequently recover the image

Utilizing the sketchViewModel for editing layers, I follow this particular logic: Upload the basic model; Edit the model; Save the edited model to localStorage; Upload the model from localStorage. However, upon uploading the model from local storage and ...

The page remains static even as the function is executed

Having trouble with creating a sliding form using jQuery. The issue is that instead of sliding to the desired page, it slides to a blank one. The website where this problem can be seen is www.entrilab.com. Upon inspecting the element, there are no errors ...

AngularJS attempting to conceal the popup menu upon clicking outside of the designated area

My HTML structure looks like this: <div> <a href="" ng-click="$scope.show_menu = !$scope.show_menu">Options</a> <div class="options_box" ng-show="$scope.show_menu"> <button>Option1</button> ... ...

Unable to generate a fresh directory with mongoose and express

As the title suggests, I am working on an application that generates a link using mongoose _id and express's app.get when certain information is inputted. However, I am facing an issue where I have to reload the entire server in order to access the di ...

Exploring the process of defining directives with Vue 3's composition API

How can directives be defined and used in Vue3's composition API using the new syntactic sugar in SFC <script setup> format? In the past, with the options API, it looked something like this: import click_outside from "@/directives/click-out ...

retrieving data from GET variables and sending to a PHP array

Is there a way to retrieve form variables and store them in an array in memory without reloading the page? I'm not very experienced with this, so any guidance would be appreciated. My goal is to update a JSON file using PHP based on form inputs. JSON ...

I'm facing an issue with converting my object to an array as I keep getting the message: "ERROR TypeError: undefined

ERROR TypeError: undefined is not a function Why am I unable to convert my object to an array? This error keeps popping up as I attempt to map all the items that are currently objects but need to be converted into arrays for mapping. How can I accomplish ...

The form is refusing to submit even after using the "return false

Even after adding validation to the form, it still submits when the script returns false. The Form Submission <form action=payment.php method=POST name=UserForm id=UserForm onsubmit="return check(this); return false;"> Javascript Code function ch ...

Utilizing the power of async/await in combination with the versatile Bluebird library to seamlessly

I'm currently developing a library that utilizes the power of async/await. My main concern is whether or not it's possible to integrate native modules like fs smoothly with async/await. As far as I understand, async/await is essentially just synt ...

Customizing Ext JS/Sencha Chart framework based on certain conditions

As someone who is new to Ext JS and Sencha charts, I have encountered a challenge with one of the charts in our application. Specifically, I needed to hide the dashes on the X-Axis of that particular chart. Our application is built using Ext JS version 5.1 ...

Looping through an array of data retrieved from the MS Graph API

When using node to call the MS Graph API with v1.0/users, the returned data shows a list of users in the following format after doing a console.log(users): { [ { displayName: "bob dole" }, { displayName: "steve st ...

Sending a form using an AngularJS dropdown menu

I have recently started using angularjs and decided to switch out a traditional html <select> box for an angular modal select box. The select box successfully populates with data from a $http ajax request, but I am facing issues with form submission ...

I'm running into a "timeout" issue with socket.io and a self-signed SSL connection. Can anyone help me troubleshoot this?

After setting up a nodejs server with HTTPS, everything seems to be working fine when sending GET requests. However, I encountered an error message 'WebSocket was closed before the connection was established' when trying to connect another nodejs ...

Enhance Your Highcharts Funnel Presentation with Customized Labels

I am working on creating a guest return funnel that will display the number of guests and the percentage of prior visits for three categories of consumers: 1 Visit, 2 Visits, and 3+ Visits. $(function () { var dataEx = [ ['1 Vis ...

When incorporating Vue as an npm package, a Vue 3 app may inadvertently clear the mounted element upon initialization

I have a straightforward Vue 3 application that is working perfectly fine when I include Vue as a script, as shown in the code snippet below. However, I need to integrate it with webpack by including it as an npm package. When I do this, the app loads but ...

Unable to execute functions using an AJAX request

Currently, I am developing a React component that is bound to various actions. During this process, I found the need to call an API from within the component and handle the response accordingly. To achieve this, here is my current approach: In a successfu ...

The checkbox must be checked for the conditional form to appear, experiencing a Safari bug in version 12.2. No issues found in Chrome and Firefox browsers

My form includes a billing address section with a checkbox that automatically sets the shipping address to match the billing address. If the user unchecks the checkbox, another form will appear below for entering a different shipping address. The Checkbox ...

Is it possible for me to include a variable with the xmlhttp response text?

There is a function defined as follows: function call_view_details(viewid) { view_details(viewid); setInterval(function(){view_details(viewid)},5000); } which I invoke when the page loads. Its main purpose is to set intervals for view_details(). ...

When utilizing a script to deliver a true or false response for jQuery's .load() function

Currently, I have found myself delving deep into jquery to manage the ajax requests in my web applications. Specifically, I am working on a bidding system in PHP that heavily relies on mod_rewrite. Using jQuery with a confirm dialog, I send an Ajax request ...

What is the most efficient way to update a specific element in a redux/vuex store?

What is the most efficient way to update an element(hash) in a list within a store (redux, vuex) using O(1) complexity? The order of the elements must be maintained as I will be adding/removing elements frequently. Updates will occur every millisecond, re ...