promise.then()必须要求.then前面是一个promise吗?
发布于 8 年前 作者 oyosc 6281 次浏览 来自 问答

getUserByName(‘nolan’).then(function (user) { if (user.isLoggedOut()) { throw new Error(‘user logged out!’); // throwing a synchronous error! } if (inMemoryCache[user.id]) { return inMemoryCache[user.id]; // returning a synchronous value! } return getUserAccountById(user.id); // returning a promise! }).then(function (userAccount) { // I got a user account! }).catch(function (err) { // Boo, I got an error! }); 看了一下promise文档,显示then()是其promise原型的方法,但是这段代码里有可能返回了一个数值,那为什么后面还可以接.then()方法呢?或者是当返回了数值的时候,直接进行了输出呢,求有经验的大虾告诉下

3 回复

不要求, then之前如果返回的是值, 则then中就是数值, 相当于执行了 promise.resolve()方法

1楼正解,你返回的值并不是直接往外层传递,而是给 promise 处理过的,包装过的。

恩,现在比较明白了,谢谢

回到顶部