javascript - 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”是未定义的,看起来像是在令牌检索之前执行的。
解决方案
我在您的代码中没有看到任何理由使用异步等待以外的任何内容。通过将 .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);}
推荐阅读
- node.js - Node.js 承诺、回调和异步
- ios - 检查用户是否登录到 facebook 并更改视图控制器
- python - ImportError:无法导入名称 _aligners [biopython]
- django - 使用 Django Rest Framework 在发布请求中嵌套发布请求
- machine-learning - 在每个框中制作一个带有数字的混淆矩阵
- mysql - SQL将日期传递到另一个表
- c# - 如何使用自定义构建任务扩展将测试结果文件添加到 vtsts 构建
- android - 使用 Ionic 使用相机拍摄多张照片
- python - 乳胶 jupyter 笔记本它不起作用
- powershell - Windows Server 2016 上的 AppFabric -“运行 cmdlet 'out-lineoutput' 时出错”