javascript - JS Promise 在 YDKJS 中揭示构造函数

标签 javascript es6-promise

我正在阅读 YDKJS 系列的《异步与性能》一书,但无法理解揭示的构造函数模式。

这是本书给出的示例:

function foo(x) {
  // start doing something that could take a while

  // construct and return a promise
  return new Promise( function(resolve,reject){
    // eventually, call `resolve(..)` or `reject(..)`,
    // which are the resolution callbacks for
    // the promise.
  } );
}

var p = foo( 42 );

function bar(fooPromise) {
  // listen for `foo(..)` to complete
  fooPromise.then(
    function(){
      // `foo(..)` has now finished, so
      // do `bar(..)`'s task
    },
    function(){
      // oops, something went wrong in `foo(..)`
    }
  );
}

bar( p );

我有两个问题:

  1. 我认为这样做的目的是不向外部公开解析和拒绝逻辑,这样可以很好地分离 Promise 逻辑和 .then() 接下来发生的事情之间的关注点在“监听” Promise 的函数(在本例中为 bar())中。我走上正轨了吗?

  2. 示例 foo() 让我感到困惑。在注释//start do something that might take a while中,这到底是什么?这是你的异步调用的地方吗?它不应该在 return 语句中的函数内部吗?我不明白这会如何工作。

最佳答案

I think the intention is not to expose the resolve and reject logic to the outside, which creates a good separation of concern

是的,这以及在 deferred pattern 中捕获异常的困难,另一种方法是仅向创建任务的函数公开解析器,而不向使用结果的函数公开解析器。

The example foo() confuses me. In the comment // start doing something that could take a while, what exactly is this? Is this where your async call would be?

是的,他们就是这个意思。

Shouldn't it be inside the function in the return statement?

是的,确实应该如此。一个具体的例子可能是

function delay(x) {
  return new Promise(function(resolve) { // construct and return a promise
    setTimeout(function() { // start doing something that could take a while
      resolve(); // eventually, call one of the resolution callbacks
    }, x);
  });
}

当然有可能启动任务和等待其结果是两个单独的语句,因此理论上它们可以分开:

function ajax(x) {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", x);
  xhr.send(); // start doing something that could take a while

  return new Promise(function(resolve, reject) { // construct and return a promise
    xhr.onload = resolve;
    xhr.onerror = reject; // eventually, call one of the resolution callbacks
  });
}

但这是一个不好的做法,因为当newopensend抛出时你不会得到一个被拒绝的 promise ,但一个异常(exception)。因此 var xhr = ... 中的所有内容都应该位于 Promise 构造函数回调内。

关于javascript - JS Promise 在 YDKJS 中揭示构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45330089/

相关文章:

javascript - CSS Transition Flicker替换背景图像和反转文本

javascript - 如何根据 JavaScript/jQuery 中查询字符串的值执行 if 条件?

javascript - 带有异步/等待的 super 代理/ super 测试

javascript - 我是在正确地链接 Promise 还是犯了罪?

javascript - 如何创建一个返回现有 promise 而不是新 promise 的函数?

javascript - 如果绑定(bind),Bootstrap CSS table-striped 不能与 knockout 一起使用

javascript - 我可以从 jquery removeClass 模拟回调函数吗?

php - 在javascript中嵌入php变量时出现"SyntaxError: unterminated string literal"错误

javascript - 在 Node js失败后重试自己

javascript - 理解 d3 中的 Promise