JS 承诺:实现与解决 [英] JS Promises: Fulfill vs Resolve

查看:22
本文介绍了JS 承诺:实现与解决的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解 Promise 存在于以下三种状态中的一种:Promise 可以是 pending(未解决)、实现(成功解决)或 拒绝strong>(解决不成功).

通读A+ Promise SpecMDN 的文档,我很困惑他们都承认实现了rejected 状态,但在 Promise 构造函数的定义中,它们指定了两个回调:resolvereject.似乎我们交替使用这两个术语;他们不是.

不代表成功:

re·solve/rəˈzälv/动词1. 解决或找到(问题、争议或有争议的事项)的解决方案.

<小时>

是否意味着成功:

ful·fill/fo͝olˈfil/动词1. 完成或实现;实现或实现(期望的、承诺的或预测的).2. 按要求、承诺或预期执行(任务、职责或角色).

当我们实际上履行承诺时,为什么我们在这里使用resolve?是否存在我们传递给 resolve 的值可能导致 Promise 被拒绝的情况?

解决方案

确实,resolve 回调并不意味着承诺会实现.

术语已完成、已拒绝、待处理、已解决、已解决锁定定义在EcmaScript2015 规范,25.4 Promise 对象::><块引用>

任何 Promise 对象都处于三种互斥状态之一:fulfilledrejectedpending:

  • 一个承诺 p 如果 p.then(f, r) 将立即排队一个 Job 以调用函数 f>.

  • 承诺 p 被拒绝,如果 p.then(f, r) 将立即排队一个作业以调用函数 r>.

  • 如果一个 promise 既未完成也未拒绝,则它处于待处理状态.

如果一个承诺不是待定的,即它被履行或被拒绝,则它被称为 settled.

一个 promise 被resolved,如果它被解决或者它已经被锁定"以匹配另一个 promise 的状态.尝试解决或拒绝已解决的承诺没有任何效果.如果 promise 没有被解决,它就是 unresolved.未解决的承诺始终处于挂起状态.已解决的承诺可能处于待定、履行或拒绝状态.

一个简短的概述,我将使用术语自治";与锁定"相反.它们是 promise 依赖情况的两个可能值:

<头>
动作依赖state解决了吗?解决了吗?
new Promise((resolve, reject) => ...)自主待定nono
...resolve(thenable)锁定待定*no
...resolve(other)自主完成
...reject(any)自主拒绝

* thenable 现在可以控制我们的 promise 对象的未来状态.

上面的引用提到了一个承诺被锁定以匹配另一个承诺"的状态,但更准确地说,另一个承诺"是匹配的.也可以是非承诺的thenable"从流程描述的步骤 11 和 12 中可以看出25.4.1.3.2><块引用>

  1. 如果 IsCallable(thenAction) 为 false,则
    一个.返回 FulfillPromise(promise,resolution).
  2. 执行 EnqueueJob("PromiseJobs"、PromiseResolveThenableJob、«‍promise、resolution、thenAction»)

使用 thenable 调用 resolve 的演示,然后触发拒绝:

const thenable = {//可以是一个 promise 对象,但不一定是然后(成功,失败){setTimeout(() => fail("gotcha!"), 1000);}}const p = new Promise((resolve, reject) => {console.log("1. 承诺被创建为待定");setTimeout(() => {解决(然后可以);console.log("2. 已通过 thenable 解决;尚未解决");}, 1000);});p.catch(err =>console.log(`3. 以错误消息 "${err}"` 被拒绝);

I understand Promises to exist in one of three states: A Promise can either be pending (unresolved), fulfilled (resolved successfully) or rejected (resolved unsuccessfully).

Reading through the A+ Promise Spec and MDN's documentation, I am confused that they both acknowledge the fulfilled and rejected states but in the definition of the Promise constructor they specify two callbacks: resolve and reject. It seems we're using these two terms interchangeably; they are not.

Does not imply success:

re·solve /rəˈzälv/ verb
1. settle or find a solution to (a problem, dispute, or contentious matter).


Does imply success:

ful·fill /fo͝olˈfil/ verb
1. bring to completion or reality; achieve or realize (something desired, promised, or predicted).
2. carry out (a task, duty, or role) as required, pledged, or expected.

Why are we using resolve here when we're actually fulfilling the Promise? Is there an instance in which the value we pass to resolve might result in the Promise being rejected?

解决方案

Indeed, the resolve callback does not imply that the promise will be fulfilled.

The terms fulfilled, rejected, pending, settled, resolved and locked-in are defined in the EcmaScript2015 specs, 25.4 Promise Objects:

Any Promise object is in one of three mutually exclusive states: fulfilled, rejected, and pending:

  • A promise p is fulfilled if p.then(f, r) will immediately enqueue a Job to call the function f.

  • A promise p is rejected if p.then(f, r) will immediately enqueue a Job to call the function r.

  • A promise is pending if it is neither fulfilled nor rejected.

A promise is said to be settled if it is not pending, i.e. if it is either fulfilled or rejected.

A promise is resolved if it is settled or if it has been "locked in" to match the state of another promise. Attempting to resolve or reject a resolved promise has no effect. A promise is unresolved if it is not resolved. An unresolved promise is always in the pending state. A resolved promise may be pending, fulfilled or rejected.

A short overview, where I will use the term "autonomous" as the opposite of "locked in". They are the two possible values for a promise's dependency situation:

action dependency state resolved? settled?
new Promise((resolve, reject) => ...) autonomous pending no no
...resolve(thenable) locked-in pending* yes no
...resolve(other) autonomous fulfilled yes yes
...reject(any) autonomous rejected yes yes

* The thenable is now in control over the future state of our promise object.

The above quote mentions that a promise is locked-in to match the state "of another promise", but more precisely that "other promise" could also be a non-promise "thenable" as can be seen in the steps 11 and 12 of the process description in 25.4.1.3.2

  1. If IsCallable(thenAction) is false, then
          a. Return FulfillPromise(promise, resolution).
  2. Perform EnqueueJob ("PromiseJobs", PromiseResolveThenableJob, «‍promise, resolution, thenAction»)

A demo of resolve being called with a thenable, which in turn triggers a rejection:

const thenable = { // Could be a promise object, but does not have to be
    then(success, fail) {
        setTimeout(() => fail("gotcha!"), 1000);
    }
}

const p = new Promise((resolve, reject) => {
    console.log("1. The promise is created as pending");
    setTimeout(() => {
        resolve(thenable);
        console.log("2. It's resolved with a thenable; it's not yet settled");
    }, 1000);
});

p.catch(err => 
   console.log(`3. It's settled as rejected with error message "${err}"`)
);

这篇关于JS 承诺:实现与解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆