传说和承诺



由于这个API请求,我的头在桌子上撞了几分钟…

我有以下代码:

传奇:

export function * registerFlow () {
  while (true) {
    const request = yield take(authTypes.SIGNUP_REQUEST)
    console.log('authSaga request', request)
    let response = yield call(authApi.register, request.payload)
    console.log('authSaga response', response)
    if (response.error) {
      return yield put({ type: authTypes.SIGNUP_FAILURE, response })
    }
    yield put({ type: authTypes.SIGNUP_SUCCESS, response })
  }
}

API请求:

// Inject fetch polyfill if fetch is unsuported
if (!window.fetch) { const fetch = require('whatwg-fetch') }
const authApi = {
  register (userData) {
    fetch(`http://localhost/api/auth/local/register`, {
      method  : 'POST',
      headers : {
        'Accept'        : 'application/json',
        'Content-Type'  : 'application/json'
      },
      body    : JSON.stringify({
        name      : userData.name,
        email     : userData.email,
        password  : userData.password
      })
    })
    .then(statusHelper)
    .then(response => response.json())
    .catch(error => error)
    .then(data => data)
  }
}
function statusHelper (response) {
  if (response.status >= 200 && response.status < 300) {
    return Promise.resolve(response)
  } else {
    return Promise.reject(new Error(response.statusText))
  }
}
export default authApi

API请求确实返回一个有效的对象,但是Saga调用的返回始终是未定义的。谁能告诉我哪里错了?

提前感谢!

最诚挚的问候,

布鲁诺

您忘记从您的函数中return承诺。让它

const authApi = {
  register (userData) {
    return fetch(`http://localhost/api/auth/local/register`, {
//  ^^^^^^
      method  : 'POST',
      headers : {
        'Accept'        : 'application/json',
        'Content-Type'  : 'application/json'
      },
      body    : JSON.stringify({
        name      : userData.name,
        email     : userData.email,
        password  : userData.password
      })
    })
    .then(statusHelper)
    .then(response => response.json());
  }
};

相关内容

  • 没有找到相关文章

最新更新