Returning the expected value returns a promise? (es7 async / wait)

const ret = () => new Promise(resolve => setTimeout( () => resolve('somestring'), 1000));

async function wrapper() {
    let someString = await ret();
    return someString;
}

console.log( wrapper() );

He is recording Promise { <pending> }; Why does it return Promise instead 'somestring'?

I am using the Babel ES7 preset to compile it.

+4
source share
2 answers

Asynchronous functions return promises. To do what you want, try something like this

wrapper().then(someString => console.log(someString));

You can also expect from wrapper(), like other promises, the context of another asynchronous function.

console.log(await wrapper());
+7
source

if you want your async function to immediately return a value, you can use Promise.resolve (theValue)

async waitForSomething() {
    const somevalue = await waitForSomethingElse()
    console.log(somevalue)

    return Promise.resolve(somevalue)
}

IMO for async waiting for keywords, one more thing is needed, allow

  return resolve 'hello'

resolve 'hello'
+2

Source: https://habr.com/ru/post/1656480/


All Articles