so i have a function that would return a promise , and in case of error I have to call the same function again but the problem that whenever i call it again the same response i would get as if the function never called again and it using the same res before.
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; } })(); }); };
^^ am just generating a token here that gona used 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 , here am getting the same response over and over again
** sorry for the misleading title , i didnt knew how to explain the problem
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