[英]“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.