REDUX THUNK ASYNC AWAIT返回Promise中间件

时间:2019-03-14 04:06:46

标签: react-redux redux-thunk redux-promise-middleware

我有一个问题,我正在使用redux thunk作为我的API中间件,并且当它只是更新redux状态时它可以正常工作。但是,我的代码中有些部分要求我从请求API获得响应,而不是等待它通过redux存储。.我如何“承诺”这部分?

我用axios调用api的代码:

export async function callApi(apiRoutes, method, params) {
  method = method.toUpperCase();
  let apiArr = apiRoutes.split('/')
  let newApiRoute = await Promise.all(apiArr.map(async (queryBreakDown, index) => {
    let value
    if (queryBreakDown.indexOf(':') > -1) {
      queryBreakDown = queryBreakDown.replace(':', '');
      if (!params) throw Error('No Params');
      value = params[`${queryBreakDown}`];
      delete params[`${queryBreakDown}`];
      return value;
    } else {
      value = queryBreakDown
    }
    return value
  }))
  newApiRoute = await newApiRoute.join('/')

  // NOTE: add pagination queries
  if (params && params.count) {
    newApiRoute += '?count=' + params.count
    delete params.count
    if (params.page) {
      newApiRoute += '&page=' + params.page
      delete params.page
    }
    //NOTE: add filters to query
    if (params.filter) {
      for (var property in params.filter) {
        newApiRoute += `&filter[${property}]=` + params.filter[`${property}`]
      }
      delete params.filter
    }
  }

  // NOTE: add file upload queries
  if (params && params.fileType && !params.count) {
    newApiRoute += '?fileType=' + params.fileType
    delete params.fileType
  }

  let data = params ? params : null
  // cookie.set('user_token', '123123123');
  // cookie.remove('user_token', { path: '' });
  let accessToken = cookie.get('user_token');
  let headers = {};
  if (accessToken) {
    headers['Authorization'] = `Bearer ${accessToken}`;
  }
    headers['Content-Type'] =  'application/json';
  const response = await axios({
    method: method,
    baseURL: host + '/api',
    url: newApiRoute,
    headers,
    data
  });

  return response
}

我的redux thunk api中间件:

export default store => next => (action) => {

  const apiRoutes = action[CALL_API];


  const { method, types, params } = action;

  next({ type: types[0] });

  return callApi(apiRoutes, method, params).then(
    response => next({
      response,
      type: types[1],
    }), error => next({
      error: (error && error.message) || 'Something bad happened',
      type: types[2]
    })
  )
}

我需要立即从中获得返回值的函数,其中getS3UploadUrl将getS3UploadUrl调度到api中间件:

  let signedURL = getS3UploadUrl({
      fileType: compressedImage.type
    })

可能我需要为signedURL返回一个值作为API请求的响应

但是,signedURL未定义。

1 个答案:

答案 0 :(得分:0)

function mapDispatchToProps (dispatch) {
  return {
    getS3UploadUrl: function(params) {
      return dispatch(getS3UploadUrl(params))
    }
  }
}

我没有为发运的OMG ..脸掌键入RETURN。

另外,我注意到,如果我的callApi函数是同步的而不是异步的,那会更好