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

Tips for inputting information without redundancy after selecting a specific designation

I'm experiencing a challenge with this code as it repeats when already chosen. My goal is to add data in the database once something has been selected. When I click on spin, the randomizer will choose a name and update their status to "done". Subsequ ...

What is the best way to eliminate "?" from the URL while transferring data through the link component in next.js?

One method I am utilizing to pass data through link components looks like this: <div> {data.map((myData) => ( <h2> <Link href={{ pathname: `/${myData.title}`, query: { ...

Struggling to find the definition of a Typescript decorator after importing it from a separate file

Consider the following scenario: decorator.ts export function logStuff(target: Object, key: string | symbol, descriptor: TypedPropertyDescriptor<any>) { return { value: function (...args: any[]) { args.push("Another argument ...

Create a POST request to the server using Express.js

I'm facing a minor problem with something I had assumed was doable. I am aiming to create two express routes – one as a GET route named /post-data and another as a POST route called /post-recieve. The code snippet would appear like the following: ...

Button click not functioning to switch the displayed image in Javascript

As a beginner in Javascript, I'm attempting to create a basic button in html that switches the originally shown image when clicked. Unfortunately, my current code isn't functioning properly. Could someone please assist me in identifying the mista ...

Helping React and MUI components become mobile responsive - Seeking guidance to make it happen

My React component uses Material-UI (MUI) and I'm working on making it mobile responsive. Here's how it looks currently: But this is the look I want to achieve: Below is the code snippet for the component: import React from 'react'; i ...

Is it necessary to use callbacks when using mongoose's findbyid with express to retrieve an object from the database? Are callbacks still important in modern JavaScript frameworks?

I'm currently exploring the express local library tutorial on MDN docs and wanted to try out returning an object without relying on a callback method. When I provide the request object parameter for the id to the findById mongoose method like this va ...

What is the best way to set up TypeScript to utilize multiple node_modules directories in conjunction with the Webpack DLL plugin?

Utilizing Webpack's DllPlugin and DllReferencePlugin, I create a distinct "vendor" bundle that houses all of my main dependencies which remain relatively static. The project directory is structured as follows: project App (code and components) ...

Difficulty adding extra arguments to a function

I am currently working on a function in d3 that aims to evaluate the "time" of my data and determine if it falls within specific time intervals. This will then allow me to filter the data accordingly. //begin with a function that checks if the time for eac ...

When the request's credentials mode is set to 'include', the 'Access-Control-Allow-Origin' header in the response should not be using the wildcard '*'

I am encountering an issue with my socket.io server as I am unable to connect to it from my local HTML file on my Mac. Error: Failed to load : The 'Access-Control-Allow-Origin' header in the response is causing a problem due to the wildcard ...

What is the best way to conceal an element in jQuery by utilizing a JavaScript variable?

I have encountered a challenge in concealing this specific page element in the provided html code <table cellspacing=5 cellpadding=3> <tr> <td id="lst2"><h4>Apple Ipad for sale N70,000 (negotiable)</h4></td> & ...

Is it possible to modify parameter values while transitioning?

While transitioning, I need the ability to modify parameter values. After researching the documentation, I discovered a method called `params('to')` that allows accessing target state's parameters. This is how it looks in my code: $transiti ...

Taking steps when a number is enclosed within a span

Testing a simple code with similar action to what I want. Apologies for any language errors, hoping to be understood :-) The HTML code snippet: <div class="pagination"> <a href="#" class=""><span>1</span></a> <a href=" ...

How to deal with jQuery's set val() behavior on SELECT when there is no matching value

Let's say I have a select box like this: <select id="s" name="s"> <option value="0">-</option> <option value="1">A</option> <option value="2" selected>B</option> <option value="3">C</option> </ ...

The use of jQuery.parseJSON is ineffective for a specific string

Why isn't jQuery.parseJSON working on this specific string? ({"stat":"OK","code":400,"data":[{"title":"Development Convention","event_type":false,"dates_and_times":[{"date":"28\/03\/2012","start_time":"10:00 AM","end_time":"10:00 AM"},{"dat ...

Tips for displaying a combobox popover from @reach/combobox within a MUI dialog element

I've been attempting to integrate a map from the Google Maps API and a combobox popover from @reach/combobox within a MUI dialog component. However, I've encountered an issue where the combobox popover isn't displaying. After some investigat ...

Receiving CORS response from the server for just one of the two API calls

Description of the issue: I am facing a peculiar problem where I am encountering different responses while making two calls to the same API. One call is successful, but the other returns a 504 error. Access to XMLHttpRequest at '' from orig ...

Unable to obtain return value in AngularJS controller or view

I have been working on a geolocation and reverse geocoding application. I have a function that is triggered by a button click to call a function in my controller which then calls my service. While the service is able to retrieve values, I am unable to get ...

Having trouble adjusting the label fontSize in ReactJS when using semantic-ui-react?

Is there a way to decrease the size of the label for a form input? In this scenario, attempting to set the fontSize does not work: <Form.Input label="Username" style={{fontSize: '10px'}} /> Does anyone have any suggestions on how to res ...

Tips on running jQuery scripts when a div changes its display style from none to block?

Is there a way to trigger jQuery code when the style of a div transitions from `display: none;` to `display: block;`? I am working with tabs, which is why this div's style changes in this manner. The jQuery code should only be executed when this spec ...