Methods
(static) addTimeLimit(asyncFunc, timeout) → {function}
Convert an async function by appending an argument represents time limit.
Parameters:
Name | Type | Description |
---|---|---|
asyncFunc |
function | a function returns a promise |
timeout |
number | in milliseconds |
Returns:
receiving same arguments as the origin, but the returned promise would auto-reject after timeout
milliseconds
- Type
- function
Example
/// convert `fetch()` to auto-reject after 3 seconds.
const fetchAutoReject = addTimeLimit(fetch, 3000);
(static) promisify(func, moreThanOneDataopt) → {function}
Simulate util.promisify
of Node.js
.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
func |
function | a function taking an error-first callback as its final argument in all cases. |
||
moreThanOneData |
boolean |
<optional> |
false | wheather callback has more than one arguments having data. |
Returns:
a function returns promise
- Type
- function
(static) wait(ms, fulfillopt) → {Promise}
Resolves after ms
milliseconds.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
ms |
integer | ||
fulfill |
* |
<optional> |
what to be resolved |
Returns:
never rejects
- Type
- Promise
(static) waitFor(sth, timeoutopt) → {Promise}
Resolves until the callback runs or the promise resolve, or rejects with an abort event until timeout
milliseconds passed. Also a shortcut to waitForEvent
.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
sth |
Promise | function | Object | if neither a promise nor a function, then |
|
timeout |
number | string |
<optional> |
non-positive number and NaN would cause the promise never reject |
Returns:
- Type
- Promise
Examples
/// rejects if `fetch()` does not resolves in 1 second.
waitFor(fetch(myURL), 1000)
.then(resp => console.log("success"), err => console.error(err));
/// similar to "promisify and run", but callbacks could be not error-first
waitFor(cb => chrome.runtime.sendMessage(myMessage, cb))
.then(resp => doSomething(resp));
/// rejects if no click to `document.body` in 1 second
waitFor({target: document.body, type: "click"}, 1000)
.then(() => console.log("a click event in 1 second is detected"));
/// same as above
waitForEvent(document.body, "click", 1000)
.then(() => console.log("a click event in 1 second is detected"));
(static) waitUntilTrue(asyncFunc, checkInterval, timeout)
Keeps calling asyncFunc
until it returns true to resolve; or timeout to reject.
Parameters:
Name | Type | Description |
---|---|---|
asyncFunc |
function | a function returns a promise |
checkInterval |
number | in milliseconds |
timeout |
number | in milliseconds; non-positive means forever. |