javascript - Eloquent Javascript (findInRemoteStorage) 。然后执行一个函数,但选择不返回解析为其返回值的承诺
问题描述
这是来自 Eloquent JavaScript 的第 11 章 - 异步编程,所有相关代码都可以在crow-tech.js和chapter/11_async.js中找到
有人可以告诉我 next() 之后的逗号在做什么吗?我的意思不是逗号运算符的作用,但为什么要这样构造呢?希望这些对 next() 的递归调用之一最终会产生一个有效的“值”——为什么需要“next(),next”?所以它再次执行 next() ,但返回......只是'next'函数对象 - 而不是解析为 next() 的返回值的承诺(这听起来像实际需要什么?)。为什么?为什么?我感到很困惑。
我知道如果不花很多时间就很难理解发生了什么,所以如果有人有一个很好的方法来回答关于特定书籍的问题,请告诉我。
.then(value => value != null ? value : next(),
next);
从:
function findInRemoteStorage(nest, name) {
let sources = network(nest).filter(n => n != nest.name);
function next() {
if (sources.length == 0) {
return Promise.reject(new Error("Not found"));
} else {
let source = sources[Math.floor(Math.random() *
sources.length)];
sources = sources.filter(n => n != source);
return routeRequest(nest, source, "storage", name)
.then(value => value != null ? value : next(),
next);
}
}
return next();
}
解决方案
有人可以告诉我 next() 之后的逗号在做什么吗?
你问的那一行:
.then(value => value != null ? value : next(), next);
将两个值传递给.then()
. .then(resolveFn, rejectFn)
因此,逗号只是将两个参数分隔为.then()
. 第一个论点是:
value != null ? value : next()
而且,第二个参数(用逗号分隔)是:
next()
它相当于这种更冗长(并带有注释)的代码表达方式:
.then(value => {
if (value != null) {
// got a value, we're done
return value;
} else {
// didn't get a value, try again with a different sources value
return next();
}
}, err => {
// got a promise reject error, try again with a different sources value
return next(err);
});
这似乎基本上只是继续调用next()
,直到它获得一个在这里可能是安全的解析值,因为每次它再次尝试时,它都会从源数组中选择一个随机值,然后删除从源数组中选择的值以进行下一次尝试. 最终,所有值都将从源数组中删除,然后它将拒绝或其中一个值将成功并完成。
推荐阅读
- python - cv2.IMREAD_GRAYSCALE 如何将 16 位图像转换为 8 位(OpenCV python)?
- plotly - python3中plotly对象的类型提示是什么
- apache-kafka - 即使在 kafka 机器重新启动后,如何保留 kafka 保留字节和 kafka 保留段
- mysql - 缓慢的 MySQL 查询,第 1 行“使用 where;使用临时;使用文件排序。” 似乎是问题
- java - 格式化负双精度时,DecimalFormat 返回奇怪的字符
- perl - 需要使用 Perl 设置和读取 cookie
- nancy - Topshelf:在 Topshelf 4.2.1 中使用 NancyFX 的问题
- python - Python idle 不允许使用通过子进程调用在 shell 中安装 Telepot
- java - 我的输出中出现随机字符,不确定它们来自哪里
- java - 是否可以在中断后重新进入while循环?