简体   繁体   English

double return 是有效的语法吗?

[英]Is double return a valid syntax?

Hi I am reading a blog on a certain website.嗨,我正在某个网站上阅读博客。

In his code he is loading data from app state using firebase.在他的代码中,他使用 firebase 从应用程序状态加载数据。 As you can see in his code.正如你在他的代码中看到的那样。 He is making double return statement.他正在做双重回报声明。 Is that a valid syntax.这是一个valid语法。 if valid what does it return?如果valid它返回什么? function or value?功能还是价值?

export const loadState = (): AppState => {

  if (firebase.auth().currentUser.uid) {
    let userId = firebase.auth().currentUser.uid;
    return firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) {
        return snapshot.val() as AppState;
      }
    }
  )
}

Let's make your code a little bit better to read让我们让你的代码更容易阅读

export const loadState = (): AppState => {

  if (firebase.auth().currentUser.uid) {
    let userId = firebase.auth().currentUser.uid;
    return firebase.database()
      .ref('/users/' + userId)
      .once('value')
      .then(function(snapshot) {
        return snapshot.val() as AppState;
      }
    }
  )
}

Now you will see that the second return is inside an inline function which is the successCallback for the Promise which is returned by Firebase.现在您将看到第二个返回位于一个内联函数内,该函数是 Firebase 返回的 Promise 的successCallback

firebase.database() returns a Promise . firebase.database()返回一个Promise The ref() and once() methods are chain functions which receive the Promise and return a new Promise which is then ultimatively passed to the then() chain. ref()once()方法是链函数,它们接收Promise并返回一个新的Promise ,然后最终传递给then()链。 Your callback returns a new Promise which then is returned as Appstate to be the return value of the loadState function.你的回调函数返回一个新的Promise ,然后返回为Appstate是的返回值loadState功能。 So loadState returns a Promise as well.所以loadState返回一个Promise

Read more about Promises on MDN 在 MDN 上阅读更多关于Promises 的信息
Read more about Firebase Database API阅读有关Firebase 数据库 API 的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM