redux-sagas发电机产量在回调内失败

时间:2016-09-12 04:00:32

标签: javascript reactjs generator firebase-authentication redux-saga

我正在尝试使用sagas中间件在firebase中设置redux注册和auth流程。但是我得到了:

Module build failed: SyntaxError: Unexpected token (16:3)

  14 |  registerUser(action.creds).then(response => {
  15 |      if(response.payload.errorCode)
> 16 |          yield put({type: 'REGISTRATION_FAILED', message: {msg_type: 'error', msg_body: response.payload.errorMessage}})
     |          ^
  17 |      else
  18 |          yield put({type: 'REGISTRATION_SUCCESSFUL', user: response})
  19 |  });

有点通用,但是围绕它移动那行代码似乎特别不喜欢在回调中。但是,我没有看到任何特别禁止的地方。有没有更好的方法来做到这一点?这是传奇发生器。

export function* registerUserSaga(action){
    console.log('registerUser called')
    console.log(action)

    registerUser(action.creds).then(response => {
        if(response.payload.errorCode)
            yield put({type: 'REGISTRATION_FAILED', message: {msg_type: 'error', msg_body: response.payload.errorMessage}})
        else
            yield put({type: 'REGISTRATION_SUCCESSFUL', user: response})
    });
}

这是firebase注册功能:

export default FireBaseTools = {
    registerUser: (creds) => {
        return firebaseAuth.createUserWithEmailAndPassword(creds.email, creds.password).then(user => {
          return user;
        }).catch(error => {
          return {
            errorCode: error.code,
            errorMessage: error.message
          }
        });
    }
}
编辑:最初我认为这是由if / else引起的,但回调似乎是真正的罪魁祸首

1 个答案:

答案 0 :(得分:0)

你应该使用来自registerUser函数的Promise;

类似的东西:

registerUser: creds => {
    return firebaseAuth.createUserWithEmailAndPassword(creds.email, creds.password)
    .then(user => ({user}) )
    .catch(error => ({error}))
}

export function* registerUserSaga(action){

    const {error, user} = yield call(registerUser,action.creds);
    error 
    ? yield put({type: 'REGISTRATION_FAILED',
               message: {msg_type: 'error', msg_body: error.message}})

    : yield put({type: 'REGISTRATION_SUCCESSFUL', user});
}