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

查看:38
本文介绍了从 then() 返回值或 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);
  });

我正在问,因为我得到了不同的行为使用 Angular 和 $http 服务和链接 .then().代码有点多,所以先看上面的例子.

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.

推荐答案

简单来说,在 then 处理函数中:

In simple terms, inside a then handler function:

A) 当 x 是一个值(数字、字符串等)时:

A) When x is a value (number, string, etc):

  1. return x 等价于 return Promise.resolve(x)
  2. throw x 等价于 return Promise.reject(x)
  1. return x is equivalent to return Promise.resolve(x)
  2. throw x is equivalent to return Promise.reject(x)

B) 当 x 是一个已经结算(不再挂起)的 Promise 时:

B) When x is a Promise that is already settled (not pending anymore):

  1. return x 等价于 return Promise.resolve(x),如果 Promise 已经被解析.
  2. return x 等价于 return Promise.reject(x),如果 Promise 已经被拒绝了.
  1. return x is equivalent to return Promise.resolve(x), if the Promise was already resolved.
  2. return x is equivalent to return Promise.reject(x), if the Promise was already rejected.

C) 当 x 是一个待定的 Promise 时:

C) When x is a Promise that is pending:

  1. return x 将返回一个挂起的 Promise,并将在后续的 then 上对其进行评估.
  1. return x will return a pending Promise, and it will be evaluated on the subsequent then.

Promise 上阅读有关此主题的更多信息.prototype.then() 文档.

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

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