首页 > 解决方案 > MSAL.JS 的异步/等待/承诺问题

问题描述

我正在尝试编写一个函数来获取承载令牌并在代表用户调用 API 之前返回标头,使用 MSAL.JS。

我想我正在为等待/异步/承诺而苦苦挣扎。我不太熟悉的东西,至少在 JS 中是这样。

这是函数(我省略了 ssoSilent/login 的部分):

const prepareAPI = async (type) => {
    const ssoRequest = {
        loginHint: _userUpn,
        scopes: ["openid", "profile", "user.read", _APIscope]
    };
    // if the user is already logged in you can acquire a token
    if (msalInstance.getAccount()) {
        var tokenRequest = {
            scopes: [_APIscope]
        };
        try {
            const resp = await msalInstance.acquireTokenSilent(tokenRequest);
            console.log(resp.accessToken);
            var headers = new Headers();
            var bearer = "Bearer " + resp.accessToken;
            headers.append("Authorization", bearer);
            resolve({
                method: type,
                headers: headers
            });

        } catch (err) {
            // could also check if err instance of InteractionRequiredAuthError if you can import the class.
            if (err.name === "InteractionRequiredAuthError") {
                return msalInstance.acquireTokenPopup(tokenRequest)
                    .then(response => {
                        return getOpts(response.accessToken, type);
                    })
                    .catch(err => {
                        console.log("Something went wrong:" + err);
                    });
            }
        }
    } else {
        // ... RequestSSO, loginPopup, etc,
    }
};

我这样调用函数:

    prepareAPI("GET")
        .then(opts => console.log("Headers: ", opts));

在解析之前,我在 console.log(resp.accessToken) 中获得了令牌。但是“opts”是未定义的,看起来像是在令牌检索之前执行的。

标签: javascriptasync-awaitpromisemsal.js

解决方案


我在您的代码中没有看到任何理由使用异步等待以外的任何内容。通过将 .then 替换为 await 并删除任何 .catch 调用来简化代码(它将改为抛出)。确保任何异步调用(解决?)都有等待语句。请记住,await 只是解析 Promise 的语法糖,它在解析时返回值或在拒绝时抛出。

前任

prepareAPI("GET")
        .then(opts => console.log("Headers: ", opts))
        .catch(e => console.error(e));

变成

try {
   const opts = await prepareAPI("GET");
   console.log("Headers: ", opts)
} catch (e) {console.error(e);}

推荐阅读