如何解决异步功能意外行为
目前,我正在开发一个通过API提供数据的Electron应用程序。渲染器调用“后端函数”,该函数首先通过Keytar获取API密钥,然后通过axios执行API调用。
这里的问题是,即使具有相同功能的相似功能正常工作也不会出现任何问题,Keytar始终返回null / undefined,这也是因为只有在完全存储了有效的API密钥的情况下,这一点才能实现由Keytar查询。
我是异步/等待功能的新手,也许我什么都没得到。
btw:也许标题不太适合,但我对此有点不知所措。
(keytarService,用户名,baseUrl为全局变量)
这是我的代码:
// api调用功能
async function makeCall(method_type,url_path,data_array) {
keytar.getPassword(keytarService,username).then((apiKey) => {
if (apiKey == null || apiKey == undefined) {
return false;
}
axios({
method: method_type,url: baseUrl + url_path,headers: {
'content-type': 'application/json','X-AUTH-TOKEN': apiKey,},data: data_array,}).then(
(response) => {
return response.data;
},(error) => {
return false;
}
);
});
}
// index_renderer.js
webContents.on('dom-ready',() => {
apiMain
.makeCall('GET','user/self')
.then((data) => {
console.log(data);
document.getElementById('username_text').innerText =
data.firstName + '' + data.lastName;
})
.catch((err) => console.log(err));
});
正在起作用的类似功能:
async function isAuthenticated() {
apiKey = await keytar.getPassword(keytarService,username);
if (apiKey == null || apiKey == undefined) {
return false;
}
axios({
method: 'GET',url: baseUrl + '/api/isAuthenticated',headers: {
'content-type': 'application/json',data: {},}).then(
(response) => {
console.log(response);
if (!response.data.authenticated) {
logout();
}
return response;
},(error) => {
console.log(error);
logout();
return error;
}
);
}
//在main.js中调用工作函数
if (authProcess.isAuthenticated()) {
mainwin.loadFile('index.html');
} else {
mainwin.loadFile('login.html');
}
谢谢。
解决方法
您在MakeCall()中缺少重要的return
。
尝试:
function makeCall(method_type,url_path,data_array) {
// return this promise to MakeCall
return keytar.getPassword(keytarService,username).then((apiKey) => {
if (apiKey == null || apiKey == undefined) {
return false;
}
// return this promise to keytar.getPassword then()
return axios({
method: method_type,url: baseUrl + url_path,headers: {
'content-type': 'application/json','X-AUTH-TOKEN': apiKey,},data: data_array,}).then(
(response) => {
return response.data;
},(error) => {
return false;
}
);
});
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。