Вызов функции JS с Ax ios внутри возвращает Undefined при вызове - PullRequest
0 голосов
/ 27 мая 2020

Функция isAdmin('foo') вернет true или false, если пользователь с псевдонимом foo имеет привязанную к нему любую из указанных ролей.

Вот код:

export function isAdmin(alias, adminRoleOverride) {
try {
    axios.get('https://xxxx.execute-api.us-west-2.amazonaws.com/xxxx/xxxx/' + alias)
    .then(function (response) {
        var admin = false;
        var aliasBoundRoles = response.data; //An array with the roles the alias currently holds.

        var adminRolePolicy = ['SuperAdmin', 'Admin', 'Director', 'RegionalManager',
            'TrainingManager', 'SiteTrainer', 'SitePOC', 'OutSourceSitePocManager']; //What is considered an admin.
        if(adminRoleOverride){
            adminRolePolicy = adminRoleOverride;
        } //If an array with roles is passed as param, override the default adminRolePolicy.

        admin = aliasBoundRoles.some((role) => {
            return adminRolePolicy.includes(role);
        }); //If any of the aliasBoundRoles is in the adminRolePolicy return true else false.
        return admin;
    });
} catch (error) {
    console.error("Error when attempting to authorize user " + alias + "."
    + "\nError: " + error);
    return false;
}  
}

I хотел бы использовать эту функцию следующим образом:

if(isAdmin('foo')){
    console.log("YAAAY")
}

.. но это не сработает, потому что при оценке if-block isAdmin('foo') все еще не определено, не вернулось.

Я знаю, что это связано с тем фактом, что вызов ax ios является asyn c и требует времени для получения данных.

Как я могу заставить это работать, любая помощь будет принята с благодарностью, и если у вас есть какие-либо руководства по этому поводу, я был бы признателен.

Ответы [ 2 ]

2 голосов
/ 27 мая 2020

вы хотите сделать следующее

export function isAdmin(alias, adminRoleOverride) {
try {
    // return the promise
    return axios.get('https://xxxx.execute-api.us-west-2.amazonaws.com/xxxx/xxxx/' + alias)
    .then(function (response) {
        var admin = false;
        var aliasBoundRoles = response.data; //An array with the roles the alias currently holds.

        var adminRolePolicy = ['SuperAdmin', 'Admin', 'Director', 'RegionalManager',
            'TrainingManager', 'SiteTrainer', 'SitePOC', 'OutSourceSitePocManager']; //What is considered an admin.
        if(adminRoleOverride){
            adminRolePolicy = adminRoleOverride;
        } //If an array with roles is passed as param, override the default adminRolePolicy.

        admin = aliasBoundRoles.some((role) => {
            return adminRolePolicy.includes(role);
        }); //If any of the aliasBoundRoles is in the adminRolePolicy return true else false.
        return admin;
    });
} catch (error) {
    console.error("Error when attempting to authorize user " + alias + "."
    + "\nError: " + error);
    return Promise.resolve(false);
}  
}

и выше

// this code should be inside an async function
const hasRoleAdmin = await isAdmin('foo')
if(hasRoleAdmin){
    console.log("YAAAY")
}
1 голос
/ 27 мая 2020

Самый простой способ получить результат asyn c при использовании Promises - использовать функцию asyn c и ждать результата:

async function codeDoingTheCheck() {
  const isAuthorized = await isAdmin('foo');
  if (isAuthorized) {
    console.log("YAAAY")
  }
}

Имейте в виду, что codeDoingTheCheck теперь также asyn c, поэтому какие бы вызовы он ни выполнял, он должен ждать своего результата (и все, что вызывает это, et c.)

...