我正试图围绕 Javascript 中令人难以置信的令人困惑的 Promises 主题。
我遇到的一个疑问是当 then()
回调实际上返回一个 promise 时会发生什么。
请看下面摘自 javascript.info 的代码
new Promise(function(resolve, reject) {
setTimeout(() => resolve(1), 1000);
}).then(function(result) {
alert(result); // 1
//Actually resolves before calling the next then()
return new Promise((resolve, reject) => { // (*)
setTimeout(() => resolve(result * 2), 1000);
});
}).then(function(result) { // (**)
alert(result); // 2
return new Promise((resolve, reject) => {
setTimeout(() => resolve(result * 2), 1000);
});
}).then(function(result) {
alert(result); // 4
});
在进入下一个 then 语句之前,任何内部 promise 实际上都已实现。
这是为什么? Javascript 如何知道返回值何时是 promise 本身?
JS 解释器中真的有检查吗?就像这样-:
if(ret_value instanceof Promise) {
wait_for_promise(ret_value);
}
这在直觉上并没有真正意义。您可能会认为返回值将保持原样,即链中的下一个 then()
将收到 promise 而不是 promise 的结果。
我有 Java 背景,这可能就是为什么这种松散的打字让我恼火的原因。
最佳答案
实际执行的检查是针对 thenables,而不仅仅是针对 Promises。
如果 Promise 解析器的返回值有一个 .then
方法,这个方法将被调用,下一个解析器/拒绝器将接收这个方法的值作为参数:
const thenable = { // simple object, not an instance of Promise per se
then: (res, rej) => setTimeout(() => res('from thenable'), 1000)
};
Promise.resolve(1)
.then(v => thenable)
.then(console.log)
关于javascript - JavaScript 如何知道等待内部 promise 的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50604836/