首页 > 解决方案 > Eloquent Javascript (findInRemoteStorage) 。然后执行一个函数,但选择不返回解析为其返回值的承诺

问题描述

这是来自 Eloquent JavaScript 的第 11 章 - 异步编程,所有相关代码都可以在crow-tech.jschapter/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();
}

标签: javascriptasynchronouses6-promise

解决方案


有人可以告诉我 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(),直到它获得一个在这里可能是安全的解析值,因为每次它再次尝试时,它都会从源数组中选择一个随机值,然后删除从源数组中选择的值以进行下一次尝试. 最终,所有值都将从源数组中删除,然后它将拒绝或其中一个值将成功并完成。


推荐阅读