Home > database >  How to return a promise with async/await that doesn't end in undefined?
How to return a promise with async/await that doesn't end in undefined?

Time:10-30

I'm doing an async/await addition function, using a given promise-creating function which should take 100ms before being called.

const delayedPromise = ms => new Promise(resolve => setTimeout(resolve, ms));

The first thing I don't understand is why there is no reject in the above Promise, and how do I handle the reject part if an error is thrown in my add function.

My code so far is

const delayedPromise = ms => new Promise(resolve => setTimeout(resolve, ms));

function validation(num1, num2) {
  if (!Number.isFinite(num1) || !Number.isFinite(num2)) {
    throw new Error('Only numbers are allowed');
  }


function add(num1, num2) {
  validation(num1, num2);
  return num1   num2;
}

// This is where I need some directions 
const addAwait = async (num1, num2) => {
  const result = await delayedPromise(add(num1, num2), 100);
  return result;
};

// My test is the following
describe.only('await calculator', () => {
  it('add works fine', async () => {
    const result = await calculator.addAwait(1, 2);
    assert.equal(3, result);
  });

I'm not passing my test and I don't understand why, it gives me AssertionError [ERR_ASSERTION]: 3 == undefined. I'm passing the two numbers to my async function, then I use the delayedPromise to create the promise and setTimeout to 100ms. It should then return a promise with the result (or error) and should make my test pass, but it doesn't. Can someone please give me some tips as to what I'm doing wrong? Thank you

CodePudding user response:

first, delayedPromise is a bit misleading. This is just a delay or pause or wait. It's not supposed to return anything but a Promise that eventually resolves.

const pause = ms => new Promise(resolve => setTimeout(resolve, ms));

// ...

const addAwait = async (num1, num2) => {
  await pause(100);  // wait for 100ms
  // then do the calculation and return the result.
  return add(num1, num2);
};

  • Related