了解 JavaScript 中的 Promise 构造函数

Understanding the Promise Constructor in JavaScript

这是来自 MDN Promise page 的代码片段。

let myFirstPromise = new Promise((resolve, reject) => {
  // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed.
  // In this example, we use setTimeout(...) to simulate async code. 
  // In reality, you will probably be using something like XHR or an HTML5 API.
  setTimeout( function() {
    resolve("Success!")  // Yay! Everything went well!
  }, 250) 
}) 

在上面的代码中,我不明白resolve(和reject)的函数定义在哪里?这里我们只是将resolve作为参数传递给Promise构造函数,然后在resolve("Success!")时调用它,那么resolve到底在哪里定义的呢?

这个有多个部分,首先这是一个 arrow function 所以:

(resolve, reject) => {}

是(以及 this 周围的一些其他内容等)的简写:

function(resolve, reject){}

所以您将一个函数作为参数传递给另一个函数。函数是 objects in JavaScript。所以如果你想象 Promise 的实现,它 可能 看起来像这样(不是实际的实现):

Promise(callBackFunction){
    ...//do some things
    callBackFunction(resolve, reject); 
}

因此,callBackFunction 是您使用箭头函数传入的函数,当 promise 到达代码中的相关点时,它将调用您的函数并传递给它 resolve, rejectresolvereject 也是这里的函数对象。

so where exactly is resolve defined

Promise 代码中。