【问题标题】:Use Async/Await and return status in React.js在 React.js 中使用 Async/Await 并返回状态
【发布时间】:2018-07-24 07:18:56
【问题描述】:

我正在尝试使用 API 调用另一个函数,在我的 ABC 函数中检查 remaing 是否可用。

如果剩余可用 retun true 否则 return false.below 是我的代码。但我的控制台日志显示 undefined。我想在我的 ABC 函数中将它作为 truefalse 获取。

export function ABC(data,callback) { 
  return  function (dispatch, getState) {  
    var res=  dispatch(Balance(data));

    console.log("Balance status",res)

    //rest of code
    if(res){
    }

    ................
 }
}

export function Balance(data) {
  return function (dispatch, getState) {
    const url = `api/.../balances`;
     axios.post(`${url}`,
      data
    ).then(async function  (response) {

      if (response.data.remaing > 0) {
        return await true;
      }else{
        return await false;

      }

【问题讨论】:

  • 我们可以在这里使用promise吗?
  • 我建议从你当前的任务中退后一步,学习一些关于 Promise 的初学者教程,以及 async/await

标签: javascript reactjs async-await react-redux axios


【解决方案1】:

对于在ABC 中创建的函数,要在其逻辑流代码中使用异步操作的结果,它必须是async 函数。您在Balance 中创建的async 函数没有任何用处,await trueawait falsethen 处理程序中也没有。

当然,如果在ABC 中创建的函数是async 函数,则调用它的代码必须是async 函数或通过promise 语法使用它。

export function ABC(data,callback) { 
  return async function(dispatch, getState) {  
  // ----^^^^^
    var res = dispatch(await Balance(data));
  // ------------------^^^^^

    console.log("Balance status",res)

    //rest of code
    if(res){
    }

    ................
 }
}

export function Balance(data) {
  return function (dispatch, getState) {
    const url = `api/.../balances`;
     axios.post(`${url}`,
      data
    ).then(function(response) {
      return response.data.remaing > 0; // ***
    });
  };
}

(真的是remaing,而不是[说] remaining?)

【讨论】:

  • 对不起,我的错误是remaing,我已经更新了我的代码。我也试过这个。但同样的错误未定义
  • @Tje123 - 那么你在代码的其他部分有类似的问题。
猜你喜欢
  • 1970-01-01
  • 2016-11-07
  • 2016-12-12
  • 2020-09-21
  • 2021-12-13
  • 1970-01-01
  • 2018-03-25
  • 2020-03-08
  • 2019-04-22
相关资源
最近更新 更多