简体   繁体   English

Javascript 中的解决和拒绝是承诺方法还是只是一些变量?

[英]Are resolve and reject in Javascript promises methods or just some variables?

take the below example code采取下面的示例代码

var promise = new Promise(function(resolve, reject) { 
const x = "geeksforgeeks"; 
const y = "geeksforgeeks"
if(x === y) { 
    resolve(); 
} else { 
    reject(); 
} 
}); 

promise. 
    then(function () { 
        console.log('Success, You are a GEEK'); 
    }). 
    catch(function () { 
        console.log('Some error has occured'); 
    }); 

The above code works fine.上面的代码工作正常。 But if I just execute the function that is passed as argument to Promise(),I get an error saying resolve is not a function.但是,如果我只是执行作为参数传递给 Promise() 的 function,我会收到一个错误,说 resolve 不是 function。

(function(resolve, reject) { 
const x = "geeksforgeeks"; 
const y = "geeksforgeeks"
if(x === y) { 
  resolve(); 
} else { 
  reject(); 
} })()

if i run the above code, i get the below error如果我运行上面的代码,我会收到以下错误

Uncaught TypeError: resolve is not a function

Can someone explain how this works?有人可以解释这是如何工作的吗?

resolve and reject come from Promise objects, but they aren't methods. resolvereject来自Promise对象,但它们不是方法。 The Promise constructor sort of looks like this: Promise构造函数看起来像这样:

class Promise {
  // handler should look like (resolve, reject) => {}
  constructor(handler) {
    function resolve(value) { /***/ }
    function reject(err) { /***/ }

    handler(resolve, reject);
  }
}

When you call new Promise(handler) with a handler of type function, the handler gets called with two functions.当您使用 function 类型的处理程序调用new Promise(handler)时,处理程序会被两个函数调用。 When you call the same handler with no arguments, the handler tries to call undefined and that's why you see the TypeError.当您调用没有 arguments 的相同处理程序时,处理程序会尝试调用undefined ,这就是您看到 TypeError 的原因。

In the first case, the function is called by the Promsie object with the required parameters resolve and reject , which would be functions.在第一种情况下,Promsie object 调用Promsie并使用所需的参数resolvereject ,这将是函数。

The reason it does not work in your second case, where you immediately invoke the function, is because you are not passing the functions to the invocation:它在第二种情况下不起作用的原因是,您立即调用 function,因为您没有将函数传递给调用:

(function(resolve, reject) { 
const x = "geeksforgeeks"; 
const y = "geeksforgeeks"
if(x === y) { 
  resolve(); 
} else { 
  reject(); 
} })(resolveFunctionHere, rejectFunctionHere) <----- HERE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM