【问题标题】:Getting response from nested Async funtion in React [duplicate]从 React 中的嵌套异步函数获取响应 [重复]
【发布时间】:2022-01-20 17:24:30
【问题描述】:

我有 3 个功能可以在我的 React Web 应用程序上登录用户。

  1. 函数 C:从登录 HTML 页面调用登录函数

 const handleLogin = (e) => {
        e.preventDefault();

        //  Calling FUNCTION B
        loginUser({ email, password }).then((value) => console.log('in promise then : ' + value));
    
        console.log('in login page: ' + response);
    };
  1. 功能B:授权

export async function loginUser(loginPayload) {

     //  Calling FUNCTION C
     AuthDataService.login(loginPayload)
      .then((response) => {
          var modifiedResponse = response;
          console.log('in AuthDataService: ' + JSON.stringify(modifiedResponse));
          return modifiedResponse;
      });
}
  1. 功能 A:调用服务器

class AuthDataService {
  async login(data) {
    return await http.post('/login', data).then((response) => {
        return response;
    });
  }
}

问题是,在函数 B 中,响应被正确记录,但在函数 A 中,响应(值)未定义。函数 C 不应该等到函数 B 完成吗? 我应该改变什么?

【问题讨论】:

  • 你没有从loginUser返回任何东西。
  • @Ivar 在console.log后面写了返回数据,还不够吗?
  • 返回一个值给(response) => { ... }回调箭头函数。不是loginUser 函数。
  • 在函数 A 的任何地方都没有声明变量response
  • 您使用哪个库来处理http 的 api 请求?如果我知道我可以测试一些东西。

标签: javascript react-native asynchronous async-await promise


【解决方案1】:

loginUser 函数没有返回任何内容。

注意:如果使用.then,则不需要异步

你可以像下面这样重构

export function loginUser(loginPayload) {
  //  Calling FUNCTION C
  return AuthDataService.login(loginPayload).then((response) => {
    var modifiedResponse = response;
    return data; // not sure from where it's coming
  });
}

类:如果你没有对响应做任何事情,那么就不需要了。

login(data) {
    return http.post('/login', data);
}

【讨论】:

    【解决方案2】:

    首先:在handleLogin 中,您没有为响应值分配任何内容。 第二:在 loginUser 和 login 你没有返回任何值。

    你可以试试这个:

    const handleLogin = async (e) => {
      e.preventDefault();
    
      const response = await  loginUser({ email, password }).then((value) => console.log('in promise then : ' + value));
    
      console.log('in login page: ' + response);
    };
    
    export const loginUser = async (loginPayload) => {
      return AuthDataService.login(loginPayload).then((response) => JSON.stringify(response));
    }
    
    class AuthDataService {
      async login(data) {
        return await http.post('/login', data)
      }
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-13
      • 2021-11-29
      • 2019-08-21
      • 1970-01-01
      相关资源
      最近更新 更多