【问题标题】:Sagas and fetch promisesSagas 和 fetch 承诺
【发布时间】:2017-02-08 11:39:55
【问题描述】:

由于这个 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 调用的返回始终是未定义的。谁能指导我哪里错了?

提前致谢!

最好的问候,

布鲁诺

【问题讨论】:

  • .catch(error =&gt; error).then(data =&gt; data) 有什么用?你真的应该忽略它们(尤其是catch,它将每次拒绝都转化为满足)
  • 你从哪里得到undefined?
  • 我在 Saga 中变得不确定,更具体地说,console.log('authSaga', response)
  • 即使我忽略它,问题仍然存在。
  • 我正在寻找与 saga 一起使用的 web-api 示例。感谢分享。

标签: javascript reactjs redux react-redux redux-saga


【解决方案1】:

你忘了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());
  }
};

【讨论】:

  • 是的,这就是问题所在!非常感谢!
猜你喜欢
  • 2021-01-28
  • 2016-10-27
  • 2020-11-09
  • 2021-06-13
  • 2016-10-28
  • 2018-05-05
  • 1970-01-01
  • 1970-01-01
  • 2016-07-15
相关资源
最近更新 更多