Typescript 响应异步函数时未定义

Typescript 响应异步函数时未定义,typescript,react-native,promise,ecmascript-6,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)

我在尝试使用异步方法时遇到问题

我有一个包含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);
    });
}

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

您需要将wait关键字与async一起使用,并且只有当您的函数具有async关键字时才可以放置wait,请尝试以下操作:

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;
    }
}
async
函数中使用
wait
。否则,返回一个承诺


不能在回调函数中返回,这并不意味着在
登录
函数中返回值,这不是上下文。

仅此一点没有帮助
loginWithCredential
仍然需要返回一些内容。无需等待,只需从api返回数据。post刚刚找到解决方案。我忘了在异步函数中添加return。它应该是“returnapi.post('…”
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)
}