[英]“Resolve” functions in JavaScript promises
我正在阅读有关如何使用Promise的文档,并且即使没有人定义“ resolve”或“ reject”函数,“ resolve”和“ reject”也经常作为参数传递给Promise构造函数。 那怎么可能? 我们在使用函数之前不必先定义函数吗?
这是一个示例:(来源: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#Browser_compatibility )
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 +
') Promise started (<small>Async code started</small>)<br/>');
// This only is an example to create asynchronism
window.setTimeout(
function() {
// We fulfill the promise !
resolve(thisPromiseCount);
}, Math.random() * 2000 + 1000);
});
它们不会作为参数传递给 Promise
构造函数。
它们由 Promise
构造函数作为参数传递到resolver
回调函数中,该函数将它们声明为参数 。
这类似于其他回调的参数,例如
array.sort(function(a, b) { … })
// ^ ^
array.map(function(element, index) { … })
// ^^^^^^^ ^^^^^
仅在Promise
构造函数回调的情况下,值是函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.