javascript 在 Promise 完成执行后设置 Promise 回调

标签 javascript asynchronous promise

在下面的代码片段中,我尝试在 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

换言之,它执行以下操作:

  1. 调用 new Promise() 构造函数
  2. Promise 构造函数调用回调
  3. 记录“创造 promise ”
  4. 回调解决了 promise
  5. 记录“已创建 Promise”
  6. 记录“调用 p.then()”
  7. 对已解决的 Promise 调用 p.then()。由于 Promise 已解决,因此会安排 .then() 回调在当前执行线程完成后立即运行。
  8. 记录“调用 p.then() 后”
  9. 当前执行线程完成,然后 Promise 调用 .then() 处理程序
  10. .then() 处理程序记录“在 .then() 处理程序中”

关于javascript 在 Promise 完成执行后设置 Promise 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34010459/

相关文章:

javascript - 我怎样才能让这个图表显示在 CSS 中的数据表旁边?

javascript - 使用 async/await 有什么好处?

JavaScript 引用理解

javascript - 在函数中将字符串与变量连接时出现无效的左侧参数错误

node.js - Mocha 异步回调和 Sequelize Promise 不同步?

javascript - 然后返回 Promise 内的 Promise 链

javascript - JS Promise - 返回一些结果而不解决 promise

javascript - 从另一个函数中的 Promise 内部返回一个值

javascript - 如何使用 fs.writeFile 从 fetch API 调用响应创建 .json 文件

javascript - NodeJS 中的嵌套回调和异常处理