我有一個承諾鏈
如果我在 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 鏈時如何實作這一點,這意味著再次執行 getUser, getServiceCost
uj5u.com熱心網友回復:
我會使用一個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...*/ });
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/362809.html
標籤:javascript 节点.js 承诺 es6-promise
