es6 里面的 promise 里的 return 是做什么的呢

2018-04-18 22:07:40 +08:00
 ghostgril

promise 只能返回一个 promise 对象,但是我总是看到一些书本和 GitHub 的代码 return 加上一个返回值的。这是为何?

3654 次点击
所在节点    问与答
9 条回复
ghostgril
2018-04-18 23:00:22 +08:00
return value 和 resolve(value)的区别在哪里呢
grantonzhuang
2018-04-18 23:03:22 +08:00
传给 then 的函数内返回的值会传给传给下一个 then 的函数
grantonzhuang
2018-04-18 23:03:31 +08:00
@grantonzhuang 绕口。。。
grantonzhuang
2018-04-18 23:03:50 +08:00
@ghostgril 传给 then 的函数内没有 resolve
murmur
2018-04-18 23:06:31 +08:00
return Promise.resolve(xxx)了解下朋友
ghostgril
2018-04-18 23:58:31 +08:00
@grantonzhuang 就是 promise 里面返回值使用 resolve,使用 return 无效?然后 then 里面使用 return 传给下一个 then 的意思
ghostheaven
2018-04-19 09:06:47 +08:00
then 和 catch 中返回 promise,会在这个 promise resolve 或 reject 的时候,把 resolve 或 reject 的结果作为参数传给后面的 then 或 catch。
如果返回普通类型的值,就直接作为参数传给下一个 then。
ghostgril
2018-04-23 17:11:03 +08:00
@ghostheaven 这个 promise 里 return 会如何呢?就是不执行后面的代码了吗
ghostheaven
2018-04-24 08:03:49 +08:00
@ghostgril 函数内任何位置 return 都会结束当前函数,不再继续之后的语句,不知道你想问的是不是这个。对于 promise 也是一样,不过结束返回后 JS 引擎会回调下一个 then 里的函数,并把返回值作为参数传过去,其实你可以使用 setTimeout 自己实现一个类似 Promise 的行为。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/447963

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX