这个承诺示例究竟是如何工作的?

How exactly does this promise example work?

我正在学习 Angular 2,我对在教程中找到的这段代码有疑问:

  appStatus = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('stable');
    }, 2000);
  });

我理解这条指令做了这样的事情:在 2 秒后将 appStatus 变量的值设置为字符串 'stable'。是这个吗?

但是 Promise 到底是什么?所以 appStatus 变量包含一个 Promise 对象引用,我认为它会包含 'stable' 2 秒后解析的值。但究竟是什么,包含什么?

Promise 的常见用例是什么?

appStatus 值不会像您想象的那样是字符串 'stable'。 appStatus 值在这里是一个承诺对象,它向您承诺字符串 'stable'(您将在 2 秒后获得它)。要从承诺中获取值 'stable'(您将在 2 秒持续时间结束时获取它),您必须执行以下操作:

appStatus.then((result) => { console.log(result); });

Promise 在 JS 的很多方面都有使用,angular 只是一个小例子。长话短说,Promise 是 .thenable objects。例如,如果您曾经使用过 xhr (XMLHttpRequest),您可以认为 .then(x) 的行为与 xhr.onload = x 类似,但这种结构允许使用更强大的代码.这两段代码作用的方式非常相似:

// callback "format"
const xhr = new XMLHttpRequest;
xhr.open('GET', '/api/some-query');
xhr.onload = () => { console.log(xhr.response); };
xhr.send();

// promise "format"
const xhrPromise = new Promise((resolve, reject) => {
  const xhr = new XMLHttpRequest;
  xhr.open('GET', '/api/some-query');
  // bad error handling, but proves the point
  xhr.onload = () => { resolve(xhr.response); };
  xhr.send();
});
xhrPromise.then((text) => { console.log(text); });

你所拥有的是使用承诺模式。为了更容易理解,这里有一个使用回调模式的类似片段:

setTimeout(() => { f('stable') }, 2000);

这是假设您将此附加到当前代码:

appStatus.then((status) => { f(status) });

一开始可能并不清楚这如何变得更好,但是一旦您深入研究它并发现 promise 是可链接的 (appStatus.then(...).then(...)),错误处理如何与 .catch 和相似,很容易爱上他们

有很多很好的读物可以理解 promise 的工作原理,例如 the MDN docs and this post by Jake Archibald