For example, there is a variable called animationComplete
(from a 3rd-party library) and a function called happenAfterAnimation
:
A simple solution looks like this:
while(!animationComplete) {
// Do nothing
}
happenAfterAnimation()
Or a more complex solution like this:
function tryHappenAfterAnimation() {
if(animationComplete) {
happenAfterAnimation()
} else {
setTimeout(tryHappenAfterAnimation, 100)
}
}
setTimeout(tryHappenAfterAnimation, 100)
The first solution may have some overheads, and the second solution looks a bit dirty.
As future/promise
is not available in current version of Javascript, it way may be a bit overkill here..
I was just wondering whether there is an elegant and lightweight way for this situation..
Does anyone have ideas about the better way to deal with this? Thanks!
Our poll function is a higher-order function that returns a function, executePoll . The executePoll function returns a promise and will run recursively until a stopping condition is met. The poll function takes 4 variables as arguments: fn : This is the function we will execute over a given interval.
Long polling in Node JS is a mechanism in which the client sends data to the server, but the server only responds until it has received complete data. Simultaneously, the client's link is open, and it is waiting for the server to reply with data before sending another query.
The first approach will not work at all. It will block the thread forever.
The absence of built-in promise support isn't really an excuse not to use promises. If your library gives you an event/callback-driven way to wait on the results (and I would be surprised if it didn't), then you should use an event, or promises.
If not, and polling the variable is really your only option, then I would say your second approach is pretty much the only option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With