1

Why do async turn a return value in to "[object Promise]"

This is the code that I would like to work....

function foo() {
    let res = bar("HELLO")
    console.log(res)
}

async function bar (text) {
    text = text + await getData();
    return (text)
}

function getData () {
    return new Promise((resolve, reject) => {
        // Do a lot of stuff to find myResult
        resolve(myResult)
    })
}

So my question is this... how come this returns HELLO

function foo() {
    let res = bar("HELLO")
    console.log(res)
}

function bar (text) {
    return (text)
}

and this returns [object Promise]

function foo() {
    let res = bar("HELLO")
    console.log(res)
}

async function bar (text) {
    return (text)
}

How do I get the async function to return the text?

torbenrudgaard
  • 2,375
  • 7
  • 32
  • 53

2 Answers2

5

An async function return value is automatically wrapped in a Promise. For you to unwrap that using the async/await syntax, you again need to await that function.

So in your case:

function foo() {
    let res = bar("HELLO")
    console.log(res)
}

Needs to become:

async function foo() {
    let res = await bar("HELLO")
    console.log(res)
}

or you can deal with it in the promise-chaining way:

function foo() {
    bar("HELLO").then(res => console.log(res))
}
Yannick Meeus
  • 5,643
  • 1
  • 35
  • 34
2

You need to use .then(). Try this.

async function bar (text) {
    return text;
}
var test = bar("hello");

test.then((value) => console.log(value));
Joven28
  • 769
  • 3
  • 12