Promise plus number returns promise

54 views Asked by At

I have a simple code

async function foo() {
  const b = bar()
  return 2 + b
}

async function bar() {
  return 2
}

(async() => {
  console.log(typeof foo())
})()

and it logs object. Not NaN. How does it happen that number + object -> object?

From what I remember from + spec if one of the operands is a primitive and second is an object then object should be converted to primitive. In this case with .valueOf() method

2

There are 2 answers

0
Kaddath On BEST ANSWER

It think it's because async functions are not resolved yet in your case, becaue there is no await. So you are getting promise objects instead of your result.

see these cases:

async function foo () {
    const b = await bar() //await result
    return 2 + b
}

async function bar () {
    return 2
}

;(async () => {
    console.log(typeof await foo()) //number
})()

async function foo () {
    const b = bar() //no await
    return 2 + b
}

async function bar () {
    return 2
}

;(async () => {
    console.log(typeof await foo()) //string
})()

0
Ele On

The functions foo and bar return a promise, so, you're getting the type of promise (Object)

Probably you want to compare the result, so you need to wait for promise resolves the concatenation:

let result = await foo();
             ^

async function foo() {
  const b = bar() // Here you need to wait as well.
  return 2 + b; // 2 + "[object Promise]"
}

async function bar() {
  return 2
}

(async() => {
  let result = await foo();
  console.log(result);
  console.log(typeof result);
})()

Now, to get the NaN value you need to convert to number:

async function foo() {
  const b = bar();  // Here you need to wait as well.
  return Number(2 + b); // <- Try to conver to number
}

async function bar() {
  return 2
}

(async() => {
  let result = await foo();
  console.log(result);
  console.log(typeof result);
})()