javascript - while 循环 promise 、链式 promise

标签 javascript promise nativescript

我有一个脚本,如果无法将用户导航到无连接页面,则应尝试连接到服务器 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/

相关文章:

尽管赋值,Javascript 类属性仍返回未定义

nativescript-vue tns 生成的应用程序获取 TypeError : Cannot read property 'on' of undefined

javascript - Node : add catch-function to promise after construction

ios - 用于负数输入字段的 NativeScript 键盘

plugins - 如何将自定义事件添加到 NativeScript UI 插件

javascript - ajax 调用何时完全完成?

javascript - 如何像实际日期字段一样使用格式化日期

javascript - 如何在不调用js(作为函数)的情况下自动运行js?

c# - 如何在 ASP.net MVC 中使用分部 View 在 Webgrid 中绑定(bind)数据

javascript - 在数组中的 promise 失败后尝试运行函数