check out my latest app: Icon Preview
and my latest blog post
Wait for a condition to be true
License: MIT License
check out my latest app: Icon Preview
and my latest blog post
This is not really an issue.
I was trying to bundle this module with babel-plugin-transform-async-to-promises
, an error throws, so I took a look at the index.js
,
Lines 36 to 44 in d4aca6d
refactor by #8
turns out this babel plugin does not support return await promise
, so this might their bug.
But, when I first saw this ESLint rule no-return-await
, I thought return await
is useless, but this try/catch
makes return promise
different with return await promise
.
Questions:
Is try/catch
the only thing in javascript makes return promise
different with return await promise
?
Why there is no rule about no-return-await
in xo
? (airbnb set no-return-await
to error
)
Can this code write in better style? I can't figure a better one
This should resolve with the return value of the function that returns the truthy value. This is useful for promise-returning functions that return either a value or undefined.
This is useful for polling operations that are guaranteed to not be complete immediately so it would make sense to start waiting for the timeout immediately instead of polling at the start.
I am using p-wait-for
version 2.0.0.
I'm seeing strange behavior when p-wait-for
times out. When I run this example code it reports that a timeout happens, but the node process does not terminate. I need to hit Control-C to terminate the process.
const pWaitFor = require('p-wait-for');
(async () =>
pWaitFor(() => false, { timeout: 1000 })
.then(() => console.log('Magically got here?'))
.catch(console.log)
)();
Result of running:
time node p-wait-for-test.js
{ TimeoutError: Promise timed out after 1000 milliseconds
at Timeout.setTimeout [as _onTimeout] (./node_modules/p-timeout/index.js:27:54)
at ontimeout (timers.js:482:11)
at tryOnTimeout (timers.js:317:5)
at Timer.listOnTimeout (timers.js:277:5) name: 'TimeoutError' }
^C
node p-wait-for-test.js 0.07s user 0.02s system 3% cpu 2.752 total
It times out after 1000 ms as expected, but the process continued until I hit Control-C after 2.752 seconds.
I would expect behavior similar to this next example, which terminates the process without my intervention:
(async () =>
Promise.reject(new Error('Failure'))
)();
If a timeout occurs which the condition function is executing, the condition function will keep on being called forever, or until it returns true. I found a similar issue #6 which was fixed in #7, but not properly fixed.
There is a clearTimeout
call once the result is settled, but it won't affect check
from calling setTimeout
again if check
was already executing (and being busy with calling condition()
.
Test:
import pWaitFor from 'p-wait-for'
let attempt = 0;
pWaitFor(async () => {
console.log(`attempt ${attempt} started`);
await new Promise(resolve => setTimeout(resolve, 500));
console.log(`attempt ${attempt++} finished`);
return false;
}, {interval: 1000, timeout: 5000}).then(console.log, console.error)
I also added some console.log
inside p-wait-for
when calling setTimeout
and clearTimeout
:
attempt 0 started
attempt 0 finished
pWaitFor: Attempt 0 failed, timer 66 set for attempt 1
attempt 1 started
attempt 1 finished
pWaitFor: Attempt 1 failed, timer 75 set for attempt 2
attempt 2 started
attempt 2 finished
pWaitFor: Attempt 2 failed, timer 84 set for attempt 3
attempt 3 started
pWaitFor: Clearing timer 84
TimeoutError: Promise timed out after 5000 milliseconds
at Timeout._onTimeout (...)
attempt 3 finished
pWaitFor: Attempt 3 failed, timer 95 set for attempt 4
attempt 4 started
attempt 4 finished
pWaitFor: Attempt 4 failed, timer 104 set for attempt 5
attempt 5 started
attempt 5 finished
pWaitFor: Attempt 5 failed, timer 113 set for attempt 6
attempt 6 started
attempt 6 finished
pWaitFor: Attempt 6 failed, timer 122 set for attempt 7
attempt 7 started
attempt 7 finished
pWaitFor: Attempt 7 failed, timer 131 set for attempt 8
...
Like falsy return values, errors could also be ignored.
await pWaitFor(() => {
assert(system.time > '10:30')
}, {ignoreErrors: error => error instanceOf AssertionError})
import pWaitFor from 'p-wait-for';
import {pathExists} from 'path-exists';
await pWaitFor(() => pathExists('unicorn.png'), {
timeout: {
milliseconds: 100,
message: MyError('Time’s up!'),
customTimers: {
setTimeout: requestAnimationFrame
}
}
});
console.log('Yay! The file now exists.');
Hello!
Thank you for this great library!
However, it's not clear from the documentation whether this library allows multiple promises to run concurrently (e.g. when one promise is not yet settled, but the next interval is reached). Looking at the code it actually waits the specified interval
time after waiting for the promise to settle. Please correct me if I'm wrong.
I would suggest to clarify this in the README.
Thanks!
Error [ERR_REQUIRE_ESM]: require() of ES Module ... is not supported
I could import and use TimeoutError directly from its sub-dependency, but that might fail if I have a different version of p-timeout installed and both are being run at the same time.
What do you think about a module that does what this does, but instead of returning a boolean:
if (typeof val !== 'boolean') {
throw new TypeError('Expected condition to return a boolean');
}
if (val === true) {
resolve();
} else {
setTimeout(check, opts.interval);
}
check for existyness (e.g. !null && !undefined
). When non-existy, keep waiting, when existy, return and pass the existy value along the promise chain.
e.g.
if (val != null) {
resolve(val);
} else {
setTimeout(check, opts.interval);
}
The current API requires variable capture which is sort of awkward. Maybe this is best done as a separate module?
Hi, I'm running node 12, webpack 3, and babel 7.8
When I start webpack dev server I get the error
Uncaught Error: Module parse failed: Unexpected token (8:2)
You may need an appropriate loader to handle this file type.
| interval: 20,
| timeout: Infinity,
| ...options
| };
When I remove that whole block, i.e. just use the options that are passed in ( which have interval and time out set ) it works.
I'm not sure why this is, it seems like it should work. but it does not.
Thanks,
why we should catch rejection, but throw nonBooleanError.
i was tring to remove this promise
Line 6 in a112539
I think this code is good enough
const check = () => {
const val = condition();
if (typeof val !== 'boolean') {
throw new TypeError('Expected condition to return a boolean');
}
if (val === true) {
resolve();
} else {
setTimeout(check, interval);
}
};
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.