【发布时间】:2019-04-19 23:25:56
【问题描述】:
JavaScript 在以下情况下工作异常。
我看到了这个答案并得到了这个关于 Javascript 奇怪行为的问题:https://stackoverflow.com/a/50173415/1614973
我发现如果我们将他代码中的then 更改为任何其他键名,我们将得到完全不同的结果。
CodePen 演示:his、changed
我试过 Chrome 和 Firefox,他们都有这个问题。 我在那里探索了问题并找到了这个“错误”的一些基本规则。
// This one will always pending
const pendingPromise = Promise.resolve(x=>x).then(r => ({ then: y => 0 }));
pendingPromise.then(r => console.log("promise resolved")); // "promise resolved" will never logged
// Thanks @Jaromanda X's correction. a simpler version is:
const pendingPromise1 = Promise.resolve().then(() => ({then: y => 0}))
pendingPromise1.then(r => console.log("promise1 resolved")); // "promise1 resolved" will never logged
pendingPromise 永远处于等待状态。据我所知,有三件事可以切换此错误:
-
原来的必须用函数来实现。(不必要的约束) - 在
.then中,必须返回一个键名为“then”的对象。 -
then键的值必须是函数。
我想知道为什么会发生这种情况。
【问题讨论】:
-
x=>x和r完全不相关,所以第 1 点是错误的……pendingPromise = Promise.resolve().then(()=>({then: y => 0}))的行为相同 -
您可以通过阅读 then 方法应该如何实现promisesaplus.com/#the-then-method 来了解您的错误
-
@Jaromanda X 你是对的。感谢您的更正。我已经改变了我的问题。
标签: javascript promise