未定义响应异步函数

时间:2017-01-05 19:09:45

标签: typescript react-native promise ecmascript-6

尝试使用异步方法时遇到了问题。

我有一个包含loginWithCredential异步函数的authServices

async loginWithCredential(username, password){
    var data = {username: username, password: password};
    api.post('/api/users/login', data)
        .then(successCallback, errorCallback)

    function successCallback(response) {
        return response.data;
    }

    function errorCallback(error){
        console.error(error);
        return false;
    }
}

在我的商店里,我尝试获取数据

@action login (user, password) {
    this.isAuthenticating = true;
    // more code above, here is the relevant setting of token
    return authServices.loginWithCredential(user, password).then(function(response){
        console.log(response);

    },function(response){
        console.log(response);
    });
}

问题是我的商店中的响应总是未定义的,因为它在返回服务之前已被触发。你对此有什么想法吗?

2 个答案:

答案 0 :(得分:0)

async loginWithCredential(username, password) {
    var data = {username: username, password: password};
    const {data} = await api.post('/api/users/login', data)
    return data;
}
@action async login (user, password) {
    this.isAuthenticating = true;
    // more code above, here is the relevant setting of token
    return await authServices.loginWithCredential(user, password)
}

您在await个函数中使用async。否则,回报承诺。

CAN NOT 在回调函数中返回,并不意味着你在login函数中返回一个值,而不是上下文。

答案 1 :(得分:-1)

你需要在async中使用await关键字,只有当你的函数有async关键字时才可以等待,试试这个:

async loginWithCredential(username, password){
    var data = {username: username, password: password};
   await api.post('/api/users/login', data)
        .then(successCallback, errorCallback)

    function successCallback(response) {
        return response.data;
    }

    function errorCallback(error){
        console.error(error);
        return false;
    }
}