函数返回promise对象而不是值

函数返回promise对象而不是值

本文介绍了函数返回promise对象而不是值(异步/等待)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I got this code using the 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'
   }
}

getSSID()等于:

看起来像getSSID()函数将始终返回promise.如何获得纯文本格式的"The value I want to return"?

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

非常感谢您的帮助.

推荐答案

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

Declaring a function async means that it will return the Promise. To turn the Promise into a value, you have two options.

常规"选项是在其上使用then():

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

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

您还可以在功能上使用await:

You can also use await on the function:

const value = await getSSID();

使用await的陷阱也必须在async函数内部.

The catch with using await is it too must be inside of an async function.

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

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):

如果要这样做,请确保该函数上有一个catch(),以捕获任何其他未捕获的异常.

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

您不能在顶层使用await.

这篇关于函数返回promise对象而不是值(异步/等待)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 07:06