javascript 函数返回承诺对象而不是值(异步/等待)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48908930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:20:26  来源:igfitidea点击:

Function returns promise object instead of value (async/await)

javascriptnode.jsasync-await

提问by Lawris

I got this code using the async/await :

我使用 async/await 得到了这个代码:

function _getSSID(){
   return new Promise((resolve, reject)=>{
      NetworkInfo.getSSID(ssid => resolve(ssid))
   })
}

async function getSSID(){
   let mySSID =  await _getSSID()
   if (mySSID == "error") {
     return 'The value I want to return'
   }
}

And getSSID()is equal to this : enter image description here

并且getSSID()等于这个: 在此处输入图片说明

Looks like the getSSID()function will always return a promise. How can I get "The value I want to return"in plain text ?

看起来该getSSID()函数将始终返回一个承诺。我怎样才能获得"The value I want to return"纯文本?

Any help is greatly appreciated.

任何帮助是极大的赞赏。

回答by samanime

Declaring a function asyncmeans that it will return the Promise. To turn the Promiseinto a value, you have two options.

声明一个函数async意味着它将返回Promise. 要将Promise转换为值,您有两种选择。

The "normal" option is to use then()on it:

“正常”选项是then()在它上面使用:

getSSID().then(value => console.log(value));

You can also use awaiton the function:

您还可以await在函数上使用:

const value = await getSSID();

The catch with using awaitis it too must be inside of an asyncfunction.

using 的问题await是它也必须在async函数内部。

At some point, you'll have something at the top level, which can either use the first option, or can be a self-calling function like this:

在某些时候,您将在顶层拥有一些东西,它可以使用第一个选项,也可以是这样的自调用函数:

((async () => {
    const value = await getSSID();
    console.log(value);
})()).catch(console.error):

If you go with that, be sure to have a catch()on that function to catch any otherwise uncaught exceptions.

如果你这样做,一定要catch()在那个函数上有一个来捕获任何其他未捕获的异常。

You can't use awaitat the top-level.

不能await在顶层使用。