Skip to content
Advertisement

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.

Advertisement

Answer

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

Advertisement