Writing a function which creates and returns a promise.
Run a given (callback) function after a delay. However:
const doShortlyExpectingTruthy = function(callback, delay, data) {
const promise = new Promise((resolve, reject) => {
let returnValue = setTimeout(callback, delay, data);
if (returnValue) {
resolve(returnValue);
} else if (!returnValue) {
reject("Falsy value");
}
});
return promise;
};
May I know how to fix this Uncaught Assertion Error.
setTimeout's return value is an integer id used to cancel the timeout, not the return value of the callback. If setTimeout worked synchronously like this, there'd be no need for the promise.
I'd break out a generic sleep function to keep the new Promise constructor out of your code, then use async/await. throw in an async function is the same as calling reject.
const sleep = ms =>
new Promise(res => setTimeout(res, ms))
;
const doShortlyExpectingTruthy = async (fn, delay, ...args) => {
await sleep(delay);
const res = fn(...args);
if (!res) {
throw Error("Falsy value retrieved");
}
return res;
};
(async () => {
console.log(await doShortlyExpectingTruthy(v => v, 1000, 42));
await doShortlyExpectingTruthy(v => v, 1000, 0);
})()
.catch(err => console.error(err))
;