【问题标题】:Async/await/promises problem with MSAL.JSMSAL.JS 的异步/等待/承诺问题
【发布时间】:2021-05-25 04:39:58
【问题描述】:

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

我想我正在为等待/异步/承诺而苦苦挣扎。我不太熟悉的东西,至少在 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”是未定义的,看起来像是在令牌检索之前执行的。

【问题讨论】:

    标签: javascript async-await promise msal.js


    【解决方案1】:

    我在您的代码中没有看到任何理由使用除异步等待之外的任何内容。通过将 .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);}
    

    【讨论】:

    • Await 仅适用于异步函数。这不会改变结果。
    • 这只是一个关于如何更新代码的示例。首先简化您的代码,然后您可以从那里检查正确性。
    猜你喜欢
    • 2021-10-07
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 2018-03-05
    • 1970-01-01
    • 2020-03-26
    相关资源
    最近更新 更多