Returning an awaited value returns a Promise? (es7 async/await)

蓝咒 提交于 2019-12-03 16:29:41

问题


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

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

console.log( wrapper() );

It logs Promise { <pending> }; Why does it return a Promise instead of 'somestring'?

I'm using the Babel ES7 preset to compile this.


回答1:


Async functions return promises. In order to do what you want, try something like this

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

You can also await on wrapper() like other promises from the context of another async function.

console.log(await wrapper());



回答2:


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

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

    return Promise.resolve(somevalue)
}

IMO the async await keywords need one more, resolve

it would be nice to write return resolve 'hello'

or just

resolve 'hello'


来源:https://stackoverflow.com/questions/39812505/returning-an-awaited-value-returns-a-promise-es7-async-await

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!