我有一个脚本,如果无法将用户导航到无连接页面
,则应尝试连接到服务器 3 次。
我不知道如何尝试连接 3 次,然后在失败时将用户导航到无连接页面
。
如何使用我的代码来解决这个问题。
这是我到目前为止的代码:
const fetchModule = require('fetch');
const frameModule = require('ui/frame');
let timeTrig;
const waitPeriod = 7000;
function checkServerStatus() {
if (timeTrig) {
clearTimeout(timeTrig);
timeTrig = null;
}
timeTrig = setTimeout(() => {
frameModule.topmost().navigate('./views/no-connection');
}, waitPeriod);
return fetchModule.fetch(`${randomUrl}auth/ping`)
.then((result) => {
clearTimeout(timeTrig);
if (result && result.ok) {
return true;
}
frameModule.topmost().navigate({
moduleName: views/no-connection,
transition: {
name: 'slide',
},
});
})
.catch(() => {
if (timeTrig) {
clearTimeout(timeTrig);
timeTrig = null;
}
frameModule.topmost().navigate({
moduleName: 'views/no-connection',
transition: {
name: 'slide',
},
});
});
}
感谢任何帮助。
最佳答案
也许这样的事情就是您想要的 - 不确定应该重试代码的哪一部分,但这可能会给您一些想法
const fetchModule = require('fetch');
const frameModule = require('ui/frame');
const waitPeriod = 7000;
// retry "cont" times or until the promise resolves
const retry = (cont, fn) => fn().catch(err => cont > 0 ? retry(cont - 1, fn) : Promise.reject(err));
// failure code - reason will be the last failure reason ('not ok' or 'timeout') - not that it is used in your code
const noConnection = reason => frameModule.topmost().navigate({
moduleName: 'views/no-connection',
transition: {
name: 'slide',
},
});
// lets race between (resolved or rejected) fetch and a rejected timeout
const doFetch = () => Promise.race([
fetchModule.fetch(`${randomUrl}auth/ping`).then(result => {
if (result && result.ok) {
return true;
}
return Promise.reject('not ok');
}),
// above can be written as
// fetchModule.fetch(`${randomUrl}auth/ping`).then(result => (result && result.ok) || Promise.reject('not ok')),
new Promise((resolve, reject) => setTimeout(reject, waitPeriod, 'timeout'))
]);
const checkServerStatus = () => {
retry(3, doFetch).catch(noConnection)
};
或者,这是相同的代码,只是组织方式不同。我认为更好:p
const fetchModule = require('fetch');
const frameModule = require('ui/frame');
const waitPeriod = 7000;
// retry "cont" times or until the promise resolves
const retry = (cont, fn) => fn().catch(err => cont > 0 ? retry(cont - 1, fn) : Promise.reject(err));
// reject after a given timeout
const delayedReject = (delay, reason) => new Promise((_, reject) => setTimeout(reject, delay, reason));
//
const doFetch = () => fetchModule.fetch(`${randomUrl}auth/ping`)
.then(result => (result && result.ok) || Promise.reject('not ok'));
const checkServerStatus = () => retry(3, () => Promise.race([doFetch(), delayedReject(waitPeriod, 'timeout')]))
.catch(reason => frameModule.topmost().navigate({
moduleName: 'views/no-connection',
transition: {
name: 'slide',
},
}));
关于javascript - while 循环 promise 、链式 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49889155/