栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

承诺重试设计模式

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

承诺重试设计模式

有点不同…

异步重试可以通过构建

.catch()
链来实现,这与更常见的
.then()
链相反。

这种方法是:

  • 只有在指定的最大尝试次数下才有可能。(链条必须是有限的长度),
  • 仅建议使用较低的最大值。(承诺链消耗的内存大致与它们的长度成正比)。

否则,请使用递归解决方案。

首先,将一个实用程序函数用作

.catch()
回调。

var t = 500;function rejectDelay(reason) {    return new Promise(function(resolve, reject) {        setTimeout(reject.bind(null, reason), t);     });}

现在,您可以非常简洁地构建.catch链:

1.重试,直到承诺解决为止

var max = 5;var p = Promise.reject();for(var i=0; i<max; i++) {    p = p.catch(attempt).catch(rejectDelay);}p = p.then(processResult).catch(errorHandler);

2.重试直到结果达到一定条件,不要拖延

var max = 5;var p = Promise.reject();for(var i=0; i<max; i++) {    p = p.catch(attempt).then(test);}p = p.then(processResult).catch(errorHandler);

3.重试直到结果满足一定条件,然后延迟

考虑到(1)和(2)之后,组合的test + delay同样是微不足道的。

var max = 5;var p = Promise.reject();for(var i=0; i<max; i++) {    p = p.catch(attempt).then(test).catch(rejectDelay);    // Don't be tempted to simplify this to `p.catch(attempt).then(test, rejectDelay)`. Test failures would not be caught.}p = p.then(processResult).catch(errorHandler);

test()
可以是同步或异步的。

添加更多测试也将是微不足道的。只需在两个鱼钩之间夹上一串炸薯条即可。

p = p.catch(attempt).then(test1).then(test2).then(test3).catch(rejectDelay);

所有版本均设计为

attempt
可返回承诺的异步功能。还可以想象它返回一个值,在这种情况下,链将遵循其成功路径到达next / terminal
.then()



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/416009.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号