如何使用条件分支处理TypeScript承诺?

时间:2018-04-11 17:51:25

标签: javascript firebase if-statement firebase-realtime-database promise

我正在访问firebase数据库,我想执行以下操作。当用户登录时,我需要检查数据库中变量的状态。根据这个变量的状态,我想做两件事之一。我的代码看起来像这样,但不是正确的。

firebase.database( ).ref( `sessions/${user.uid}` ).once( 'value' )
  .then( ( data : firebase.database.DataSnapshot ) => {
    if( !data.exists( ) ) {
      console.log( 'No active sessions. Creating a new one' );
      const sessionKey = firebase.database( ).ref( `sessions/${user.uid}` ).push( ).key;
      return firebase.database( ).ref( `sessions/${user.uid}/${sessionKey}` ).update( {
        myStruct: {
          myValue: 123,
        }
      } );
    } else {
      console.log( 'Found an existing session' );
      const obj = data.val( );
      const sessionKey = Object.keys( obj )[0];
      return firebase.database( ).ref( `sessions/${user.uid}/${sessionKey}` ).once( 'value' );
    }
  } )
  .then( ( data : any ) => {
    //what is data here?  Is it coming from the .update call, or from the .once call ??
    //if this is coming from the update call then I want to perform some stuff,
    //however if it is coming from the .once call, then I want to retrieve the myStruct.myValue and perform some other stuff.
  } )
  .catch( ( error : firebase.auth.Error ) => {
    console.log( error );
  } );

1 个答案:

答案 0 :(得分:1)

它来自任何一个返回。您可能需要将该逻辑移到另一个函数中,或者至少将所需的上下文添加到通过最终.then的对象中:

firebase...once( 'value' )
.then((data : firebase.database.DataSnapshot ) => {
  if(!data.exists()) {
    return firebase...update(/* ... */).then(
        (data: any) => {
            return {
                type: 'update',
                data: data
            }
        }
    );
  } else {
    return firebase...once('value').then(
        (data: any) => {
            return {
                type: 'once',
                data: data
            }
        }
    );
  }
}).then(( data : any ) => {
    if (data.type === 'update') {

    } else if (data.type === 'once') {

    }
});