【问题标题】:Retry functionality in promise chain承诺链中的重试功能
【发布时间】:2021-12-31 23:18:35
【问题描述】:

我有一个承诺链

如果我在 getServiceCost 中收到错误,我想再次重复该链(重试)2 次,在使用 Promise 链时如何实现这一点,这意味着再次执行 getUser、getServiceCost

getUser(100)
    .then(getServices)
    .then(getServiceCost)
    .then(console.log);


function getUser(userId) {
    return new Promise((resolve, reject) => {
        console.log('Get the user from the database.');
        setTimeout(() => {
            resolve({
                userId: userId,
                username: 'admin'
            });
        }, 1000);
    })
}

function getServices(user) {
    return new Promise((resolve, reject) => {
        console.log(`Get the services of ${user.username} from the API.`);
        setTimeout(() => {
            resolve(['Email', 'VPN', 'CDN']);
        }, 3 * 1000);
    });
}

function getServiceCost(services) {
    return new Promise((resolve, reject) => {
        console.log(`Calculate the service cost of ${services}.`);
        setTimeout(() => {
            resolve(services.length * 100);
        }, 2 * 1000);
    });
}

如果我在 getServiceCost 中收到错误,我想再次重复链(重试)2 次,使用 Promise 链时如何实现这一点,意味着再次执行 获取用户,获取服务成本

【问题讨论】:

  • 只有第三件事失败的时候,你想从开始开始?
  • 没错@T.J.Crowder

标签: javascript node.js promise es6-promise


【解决方案1】:

我会使用async 函数(所有现代环境都支持它们,并且您可以为过时的环境进行转换),它可以让您使用一个简单的循环。也许作为一个实用函数你可以重用:

async function callWithRetry(fn, retries = 3) {
    while (retries-- > 0) {
        try {
            return await fn();
        } catch (error) {
            if (retries === 0) {
                throw error;
            }
        }
    }
    return new Error(`Out of retries`); // Probably using an `Error` subclass
}

使用它:

callWithRetry(() => getUser(100).then(getServices).then(getServiceCost))
.then(console.log)
.catch(error => { /*...handle/report error...*/ });

或者

callWithRetry(async () => {
    const user = await getUser(100);
    const services = await getServices(user);
    return await getServiceCost(services);
})
.then(console.log)
.catch(error => { /*...handle/report error...*/ });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    • 2017-10-18
    相关资源
    最近更新 更多