2015-06-01 50 views
1

我正在阅读有关如何使用承诺的文档,经常将“解析”和“拒绝”作为参数传递给Promise构造函数,即使没有人定义“解析”或“拒绝”功能。这怎么可能?在使用它们之前我们不需要定义函数吗?JavaScript中的“解析”功能承诺

下面是一个例子:(来源: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); 
     }); 
+3

在您发布的代码中,'resolve'和'reject'是正式的函数参数。任何地方都没有*通过*它是函数的* definition *,这些是参数的名称。当函数实际上被称为*时,那些将引用将在别处定义的函数。 – Pointy

回答

1

他们不作为参数传入Promise构造。

它们作为参数Promise构造函数传入声明他们作为参数resolver回调函数。

这类似于其他回调的参数,例如

array.sort(function(a, b) { … }) 
//    ^^ 
array.map(function(element, index) { … }) 
//     ^^^^^^^ ^^^^^ 

仅这些值是在Promise构造回调的情况下的功能。

+0

嗯,我敢打赌,这是一个重复,但我无法找到任何。 – Bergi