【问题标题】:"Resolve" functions in JavaScript promisesJavaScript Promise 中的“解析”函数
【发布时间】:2015-08-15 02:55:42
【问题描述】:

我正在阅读有关如何使用 Promise 的文档,并且经常将“resolve”和“reject”作为参数传递给 Promise 构造函数,即使没有人定义过“resolve”或“reject”函数。这怎么可能?难道我们不需要在使用之前定义函数吗?

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

【问题讨论】:

  • 在您发布的代码中,resolvereject 是正式的函数参数。任何地方都没有通过;它是函数的定义,这些是参数的名称。当函数实际被调用时,那些将引用将在别处定义的函数。

标签: javascript constructor promise


【解决方案1】:

它们不会作为参数传入Promise 构造函数。

它们作为参数通过Promise 构造函数传递到您的resolver 回调函数中,该函数将它们声明为参数

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

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

仅在 Promise 构造函数回调的情况下值是函数。

【讨论】:

  • 嗯,我敢打赌这是重复的,但我找不到。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-18
  • 1970-01-01
  • 2020-06-27
  • 2019-04-24
  • 2020-05-23
  • 2017-07-27
  • 2020-06-10
相关资源
最近更新 更多