In this post it is mentioned that I can create a custom Promise with setTimeout
like below:
const delay = t => new Promise(resolve => setTimeout(resolve, t));
My operation needs to be executed after 100ms so t
will be 100
in my scenario.
I'm confused on how to use this though. The normal format of a Promise is new Promise (resolve, reject)
but in the delay
function only the resolve
has been defined.
Here's my attempt:
function numbersValidation(number1, number2) {
if (!Number.isFinite(number1) || !Number.isFinite(number2)) {
throw new Error('Only numbers are allowed');
}
}
function add(number1, number2) {
numbersValidation(number1, number2);
return number1 + number2;
}
const addPromise = (number1, number2) => {
delay(100)
.then(result => result = add(number1, number2));
.catch(err => reject(err));
};
// -----Test------
describe.only('promise calculator', () => {
it('add works fine', done => {
calculator.addPromise(1, 2).then(result => {
try {
assert.equal(3, result);
done();
} catch (e) {
done(e);
}
});
});
});
// AssertionError [ERR_ASSERTION]: 3 == false
This is quite wrong since my IDE is complaining about the structure, but can someone please point me in the right direction on how to use the delay function so that I make my addPromise
function work?
Thank you