在下面的代码片段中,我尝试在 promise 完成后设置 Promise
回调。
由于某种原因,在我期望 future 完成它的执行之后,它似乎“记住”执行回调。
为什么会这样?
'use strict';
var promiseCount = 0;
function testPromise() {
var thisPromiseCount = ++promiseCount;
var log = document.getElementById('log');
log.insertAdjacentHTML('beforeend', thisPromiseCount +
') Started (<small>Sync code started</small>)<br/>');
// We make a new promise: we promise the string 'result' (after waiting 3s)
var p1 = new Promise(
// The resolver function is called with the ability to resolve or
// reject the promise
function(resolve, reject) {
log.insertAdjacentHTML('beforeend', thisPromiseCount +
') the promise is started(<small>Async code started</small>)<br/>');
resolve(thisPromiseCount);
log.insertAdjacentHTML('beforeend',promiseCount+ ') the promise is supposed to finish<br/>');
});
window.setTimeout(
function() {
log.insertAdjacentHTML('beforeend', thisPromiseCount +
') we set the callback much after the proise has finished<br/>');
p1.then(
// Log the fulfillment value
function(val) {
log.insertAdjacentHTML('beforeend', val +
') and still the promise executes the callback!(<small>Async code terminated</small>)<br/>');
})
.catch(
// Log the rejection reason
function(reason) {
console.log('Handle rejected promise ('+reason+') here.');
});
}, 5000);
log.insertAdjacentHTML('beforeend', thisPromiseCount +
') Sync code terminated<br/>');
}
<button type="button" onclick='testPromise()' />test</button>
<div id="log"></div>
最佳答案
如果p
是一个已经解决的promise,然后你调用p.then(callback)
,它仍然会调用回调。这就是 promise 如何发挥作用。这符合预期。
但是,.then()
回调将在执行 p.then()
的执行线程完成执行后被异步调用(换句话说,它不会立即被调用,而是在稍微延迟后被调用)。这样,.then()
处理程序总是异步执行,无论它们所调用的 Promise 仍处于挂起状态还是已解决。这会创建一致的编程行为。
这是一个更简单的演示:
var p = new Promise(function(resolve, reject) {
log("Creating promise");
resolve();
});
log("Promise Created");
log("Calling p.then()");
p.then(function() {
log("In .then() handler");
})
log("After calling p.then()");
function log(msg) {
var div = document.createElement("div");
div.innerHTML = msg;
document.body.appendChild(div);
}
您可以运行代码片段来查看输出:
Creating promise Promise Created Calling p.then() After calling p.then() In .then() handler
换言之,它执行以下操作:
- 调用
new Promise()
构造函数 - Promise 构造函数调用回调
- 记录“创造 promise ”
- 回调解决了 promise
- 记录“已创建 Promise”
- 记录“调用 p.then()”
- 对已解决的 Promise 调用
p.then()
。由于 Promise 已解决,因此会安排.then()
回调在当前执行线程完成后立即运行。 - 记录“调用 p.then() 后”
- 当前执行线程完成,然后 Promise 调用
.then()
处理程序 .then()
处理程序记录“在 .then() 处理程序中”
关于javascript 在 Promise 完成执行后设置 Promise 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34010459/