我的问题是我每隔x秒调用一次刷新令牌函数,我在refreshToken函数中有硬编码导航到主页 因为间隔在另一个文件中声明,所以在执行导航时,函数中的不能清除间隔。
我想要的是从其他文件调用refreshToken并返回promise 是否需要将用户导航到主页(如果响应访问令牌或刷新令牌为空,则导航到主页),如果是,则清除间隔并在此之后导航。
这是refreshToken函数,它位于methods.js:
中let refreshToken=(url,refresh_token)=>{
console.log("access_token check");
let currentMin=getMinute();
if(currentMin===0){
currentMin=60;
}
if(appSettings.getNumber("tkTime") > currentMin){
currentMin=currentMin+60;
}
if(currentMin - appSettings.getNumber("tkTime") >= 4){
fetch(url,{
headers: new Headers({
'Content-Type': 'application/json',
'Authorization':`Bearer ${refresh_token}`
}),
method:'POST'
}).then((res) => {
return res.json();
}).then((data)=>{
if(data.refresh_token !== null || data.access_token !== null){
appSettings.setString("refresh_token",data.refresh_token);
appSettings.setString("access_token",data.access_token);
appSettings.setNumber("tkTime",getMinute());
console.log("token refreshed");
}
else{
topmost().navigate({moduleName:"Home/home",clearHistory: true});
}
})
.catch(error => {
console.log(error);
});
}
}
这是我从userPage.js调用此函数的代码部分:
const myModules = require('~/methods.js');
myModules.refreshToken(myModules.refUrl,appSettings.getString("access_token"),appSettings.getString("refresh_token"));
ref=timer.setInterval(() => {
myModules.refreshToken(myModules.refUrl,appSettings.getString("access_token"),appSettings.getString("refresh_token"));
},1000*30);
答案 0 :(得分:0)
从函数返回fetch并写入handle else条件,否则它将会中断。
let refreshToken = (url, refresh_token) => {
console.log("access_token check");
let currentMin = getMinute();
if (currentMin === 0) {
currentMin = 60;
}
if (appSettings.getNumber("tkTime") > currentMin) {
currentMin = currentMin + 60;
}
if (currentMin - appSettings.getNumber("tkTime") >= 4) {
return fetch(url, {
headers: new Headers({
'Content-Type': 'application/json',
'Authorization': `Bearer ${refresh_token}`
}),
method: 'POST'
}).then((res) => {
return res.json();
}).then((data) => {
if (data.refresh_token !== null || data.access_token !== null) {
appSettings.setString("refresh_token", data.refresh_token);
appSettings.setString("access_token", data.access_token);
appSettings.setNumber("tkTime", getMinute());
console.log("token refreshed");
} else {
topmost().navigate({
moduleName: "Home/home",
clearHistory: true
});
}
})
} else {
// .then will throw an error if not write
return new Promise(resolve => resolve( /*Some Data*/ ));
}
}