[英]Implicit `resolve` in JavaScript promises
I'm using promises in JavaScript with setTimeout
and I'm getting something of a mysterious behaviour.我在 JavaScript 中使用了带有
setTimeout
的承诺,我得到了一些神秘的行为。 I'm seeing things working fine and I can't explain it.我看到一切正常,我无法解释。
Let's say I have this function:假设我有这个 function:
function f(callback) {
setTimeout(() => callback(13), 3000);
}
When I call it with no callback, I get a most expected error:当我在没有回调的情况下调用它时,我得到了一个最预期的错误:
> f()
undefined
> Uncaught TypeError: callback is not a function
When I call it with an actual callback, all works fine:当我使用实际回调调用它时,一切正常:
> f(console.log)
undefined
> 13
So far, all went according to plan, but when I call f()
wrapped in a promise, it seems to no longer require the callback
parameter:到目前为止,一切都按计划进行,但是当我调用包装在 promise 中的
f()
时,似乎不再需要callback
参数:
> new Promise(f).then(console.log)
Promise { <pending> }
> 13
Going a bit slower, if I store the promise, it ends up having a value:慢一点,如果我存储 promise,它最终有一个值:
> p = new Promise(f)
Promise { <pending> }
> p
Promise { <pending> }
> p // after 3 seconds
Promise { 13 }
>
This happens on both browser and Node.这发生在浏览器和节点上。
QUESTION: How is it possible that f
doesn't complain at all for the lack of a callback
?问题:
f
怎么可能根本不抱怨缺少callback
? How is the value 13
assigned as the promise value?值
13
如何分配为 promise 值?
TL;DR === false
I know I should be counting my blessings because it's working, but documentation doesn't seem to mention any hidden default mechanism for dealing with this kind of situation that I could find. TL;DR === false
我知道我应该算我的祝福,因为它正在工作,但文档似乎没有提到任何隐藏的默认机制来处理我能找到的这种情况。 All I get is a brief intro immediately followed by a fast-forward pathway into chaining and more advanced patterns.我得到的只是一个简短的介绍,然后是一个快速前进的路径,进入链接和更高级的模式。 I need to be sure that I can replicate this behaviour with more complex cases.
我需要确保我可以在更复杂的情况下复制这种行为。
How is it possible that f doesn't complain at all for the lack of a callback?
f 怎么可能根本不抱怨缺少回调?
The function you give to a promise does receive arguments: resolve
and reject
callbacks.您提供给 promise 的 function确实收到 arguments:
resolve
和reject
回调。
A normal use of promises look like this: Promise 的正常使用如下所示:
return new Promise((resolve, reject) => {
// call resolve() on success
// call reject() on error
});
How is the value 13 assigned as the promise value?
值 13 如何分配为 promise 值?
You're calling resolve(13)
when your timeout expires.当您的超时到期时,您正在调用
resolve(13)
。
Lets move f to the promise constructor...让我们将 f 移至 promise 构造函数...
new Promise(function f(callback) {
setTimeout(() => callback(13), 3000);
}).then(console.log)
Then lets add another argument...然后让我们添加另一个参数...
new Promise(function f(callback, reject) {
setTimeout(() => callback(13), 3000);
}).then(console.log)
And rename callback to resolve:并重命名回调以解决:
new Promise(function f(resolve, reject) {
setTimeout(() => resolve(13), 3000);
}).then(console.log)
Does it look familiar?是不是很眼熟?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.