从那时起返回值或Promise.resolve有什么区别() [英] What's the difference between returning value or Promise.resolve from then()

查看:271
本文介绍了从那时起返回值或Promise.resolve有什么区别()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别:

new Promise(function(res, rej) {
    res("aaa");
  })
  .then(function(result) {
    return "bbb";
  })
  .then(function(result) {
    console.log(result);
  });

这个:

new Promise(function(res, rej) {
    res("aaa");
  })
  .then(function(result) {
    return Promise.resolve("bbb");
  })
  .then(function(result) {
    console.log(result);
  });

我问我正在使用带有链接.then()的Angular和$ http服务获得不同的行为。有点太多的代码因此首先是上面的例子。

I'm asking as I'm getting different behaviour Using Angular and $http service with chaining .then(). A bit too much code hence first the example above.

推荐答案

规则是,如果<$ c中的函数$ c>然后 handler返回一个值,promise使用该值解析/拒绝,如果函数返回一个promise,会发生什么,下一个然后子句将是函数返回的承诺然后子句,因此,在这种情况下,第一个示例属于正常序列 thens 中的值,并按照人们的预期输出值,在第二个示例中,当您执行 Promise.resolve( bbb)然后是链接时调用的然后(用于所有意图和目的)。它的实际工作方式将在下面详细介绍。

The rule is, if the function that is in the then handler returns a value, the promise resolves/rejects with that value, and if the function returns a promise, what happens is, the next then clause will be the then clause of the promise the function returned, so, in this case, the first example falls through the normal sequence of the thens and prints out values as one might expect, in the second example, the promise object that gets returned when you do Promise.resolve("bbb")'s then is the then that gets invoked when chaining(for all intents and purposes). The way it actually works is described below in more detail.

从Promises / A +规范中引用:

Quoting from the Promises/A+ spec:


承诺解决程序是一个抽象操作,将promise和值作为输入,我们将其表示为 [[Resolve]](promise,x)如果 x 是一个可用的,它会尝试承诺采用 x 的状态,假设x的行为至少有点像承诺。否则,它使用值 x 来履行承诺。

The promise resolution procedure is an abstract operation taking as input a promise and a value, which we denote as [[Resolve]](promise, x). If x is a thenable, it attempts to make promise adopt the state of x, under the assumption that x behaves at least somewhat like a promise. Otherwise, it fulfills promise with the value x.

这种对thenables的处理允许promise实现进行互操作,因为他们暴露了Promises / A +兼容的方法。它还允许Promises / A +实现用合理的方法同化不一致的实现。

This treatment of thenables allows promise implementations to interoperate, as long as they expose a Promises/A+-compliant then method. It also allows Promises/A+ implementations to "assimilate" nonconformant implementations with reasonable then methods.

这里要注意的关键是这一行:

The key thing to notice here is this line:


如果 x 是一个承诺,采用其状态 [3.4]

if x is a promise, adopt its state [3.4]

链接: https://promisesaplus.com/# point-49

这篇关于从那时起返回值或Promise.resolve有什么区别()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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