Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

269
Views
getting same response from a promise multiple times

I have a function that would return a promise, and in the case of an error, I have to call the same function again. The problem is that whenever I call it again, I get the same response, as if it was never called again.

This is how am resolving:

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;
             }
         })();
     });
 };

I'm generating a token here, which I use in the second script:

function sleep(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}
(async() =>{
while(true){
test = require("./test")
test.first_file ().then(res=>{
  console.log(res)
})
await sleep(15000)
}
})()

The expected value here is that every 15000ms (15 sec) I get a new response, but here I'm getting the same response over and over again.

Sorry if the title is inaccurate; I didn't know how to explain the problem.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Promises represent a value + time, a promise's settled value doesn't change like the number 5 doesn't change. Calling resolve multiple times is a no-op*.

What you want to do instead of using the language's abstraction for value + time is to use the language's abstraction for action + time - an async function (or just a function returning a promise)

   const tokenFactory = () => {
         let current = null;
         (async () => 
            while (true) {
              console.log("Resolving...");
              current = token; // get token somewhere
               await sleep(5000);
            }
          })().catch((e) => {/* handle error */});
          return () => current; // we return a function so it's captured 
    };

Which will let you do:

tokenFactory(); // first token (or null)
// 5 seconds later
tokenFactory(); // second token

*We have a flag we added in Node.js called multipleResolves that will let you observe that for logging/error handling

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!