javascript-当键名称为“ then”的对象时,为什么诺言未决

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

endingPromise永远待定.据我所知,有三件事可以切换此错误:

>原始功能必须具有功能. (不必要的约束)
>在.then中,必须返回键名为“ then”的对象.
>然后,键的值必须是一个函数.

我想知道为什么会这样.

最佳答案
它永远不会解决的原因是因为您的最终“ then”永远不会解决:

.then(r =>({then:y => 0}))仅返回不可补0.

y是一个解析回调.要使代码正常工作,请更改y进行解析,然后调用它.或者,只需致电y.要点是,在调用解决方案之前,承诺仍然处于待处理状态.

console.log("Starting Strange Promise")
const pendingPromise = Promise.resolve(x=>x).then(r=>(
  {then: y => "Strange Promise Done!"}
));
pendingPromise.then(console.log) // never happens

console.log("Starting Hacked Promise")
const hackedPromise = Promise.resolve(x=>x).then(r=>(
  {then: resolve => resolve("Hacked Promise Done!")}
));
hackedPromise.then(console.log)  // happens,like,speed of light quickly

相关文章

kindeditor4.x代码高亮功能默认使用的是prettify插件,prett...
这一篇我将介绍如何让kindeditor4.x整合SyntaxHighlighter代...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小