Fire off a Promise
Friday, April 19th, 2024This morning I was thinking about the interrogation of the Promise in Node, and it was a little bothering to me that there was no way to easily see if it was complete. Then I thought - Maybe there is a different way? So I decided to give this a try.
The use-case is this: I want to be able to fire off a request to another Service, and maybe it'll get back to me in time, and maybe it won't. Either way, I don't want to wait. I have other work to do that must get done. So I want to fire this Promise off, and then, if it's done when I need its result - Great! If not, then Also Great!
But the normal:
const foo = await callAsyncFunction()
isn't going to work, because that will wait until it's done. So how to work this out?
It turns out that it's not too hard.
const { setTimeout } = require('timers/promises') const runTest = async () => { let done = false const foo = setTimeout(5000).then((val) => done = true) for (let i = 0; i < 10; i++) { console.log('FOO', foo, done) await setTimeout(1000) } } runTest() .then(() => console.log('All done running Timing test.')) .catch(console.error) .finally(() => process.exit())
and when I run this:
$ node foo.js FOO Promise { <pending> } false FOO Promise { <pending> } false FOO Promise { <pending> } false FOO Promise { <pending> } false FOO Promise { <pending> } false FOO Promise { true } true FOO Promise { true } true FOO Promise { true } true FOO Promise { true } true FOO Promise { true } true All done running Timing test.
So all we need to do is to have a variable that indicates the state of the completeness, and then return that in the .then() call. Sure, it may make a lot more sense to have:
const foo = setTimeout(5000).then((val) => { done = true return val })
so that we get the value back into foo, but that's easy... the point is to toggle the variable in that .then() and query that, as needed.
This way, I don't have to worry about any unsupported ways of finding out, it's simple. 🙂