![](/img/trans.png)
[英]Promises does not wait resolve or reject - javascript - ReactJs
[英]When or who does pass resolve and reject functions to JS promises?
我已经开始学习 javascript promises。 但我就是无法理解承诺的概念。 最困扰我的是谁将 Resolver 和 Reject 函数传递给 promise 构造函数?
看这个 Promise 的例子:
function getImage(url){
return new Promise(function(resolve, reject){
var img = new Image()
img.onload = function(){
resolve(url)
}
img.onerror = function(){
reject(url)
}
img.src = url
})
}
现在谁会通过解析和拒绝方法,因为我对 javascript 的理解告诉我这个脚本会抛出未知变量错误,因为解析和拒绝没有定义?
getImage('doggy.jpg').then(function(successurl){
document.getElementById('doggyplayground').innerHTML = '<img src="' + successurl + '" />'
}).catch(function(errorurl){
console.log('Error loading ' + errorurl)
})
现在你看到了像上面这样的方法,传递这些方法(resolve 和 reject)的唯一方法是通过 then 和 catch,就像上面对 getImage 的方法调用中使用的那样。
最让我烦恼的是谁将 Resolver 和 Reject 函数传递给 promise 构造函数?
没人。
这些函数由promise 构造函数传递。
它们被传递给作为第一个参数传递给 promise 构造函数的函数。
Promise 构造函数使用回调进行初始化,构造函数在调用回调时将reject
和resolve
作为参数传递。
这是一个简单的演示:
class PromiseDemo { constructor(cb) { cb(this.resolve.bind(this), this.reject.bind(this)); } resolve(d) { console.log('resolve', d); } reject(d) { console.log('reject', d); } } new PromiseDemo((resolve, reject) => { Math.random() > 0.5 ? resolve('1') : reject('1'); });
我在理解 Promise 时遇到了同样的问题,需要仔细查看 Promise 的创建过程。 当你写var promise= new Promise(function(resolve,reject){...})
您实际上是在调用 Promise 类的构造函数或创建 Promise 类的对象。 现在 Promise 构造函数需要一个函数回调。 现在解决和拒绝只是函数参数而不是任何其他值。 您可以编写任何内容来代替解析或拒绝,例如 resolveHandler 或 rejectHandler。
这些resolve或reject不过是Promise在执行时调用的函数回调。
现在,当 Promise 成功执行时会调用 resolve ,当 Promise 执行时出现错误或不成功时会调用 reject 。
与决心被称为里面可以访问的参数then
像这样
getImage().then(function(valueSentInResolve){ console.log('')})
调用拒绝的参数可以像这样在catch
访问
getImage().then(function(valueSentInResolve)
{//..do something}
).catch(function(errorSentInReject){
console.log('error',errorSentInReject )
})
我希望这会有所帮助。如果我说错了什么,请告诉我。
承诺库创建并传递这些函数,以及跟踪承诺和记录完成、存储状态和进度、取消等所需的所有其他元数据。
Bluebird 背后的人已经发布了一些关于库内部如何工作的信息,您可以在 Bluebird 源代码中看到更多信息。
这有意义吗? 这个解释可能完全不正确!!
我们提供应该异步运行的逻辑。 逻辑应该接受 2 个函数, resolve
和reject
。 这些函数的引用由Promise
提供。 当我们有最终值或错误时,这些函数应该由我们的逻辑调用。 最初创建的Promise
处于Pending
状态。 调用resolve
和reject
将状态分别更改为Fulfilled
或Rejected
。
executeFunction(res,rej) = {
do some op, say DB query.
if (success) res(value) //executeFunction uses the resolving functions to change state of the Promise. Calling res fulfills the promise with value
if (fail) rej(reason)//executeFunction uses the resolving functions to change state of the Promise. Calling rej rejects the promise with reason
}
我们不是直接调用executeFunction
(这将使调用同步),而是创建一个 Promise 将在单独的线程中运行executeFunction
代码(异步) let p = Promise(executeFunction(res,rej));
. 我们取回了 Promise 的引用。
我的猜测是在Promise
内部,会发生以下情况
Promise(e(res,rej)) = {
// the Promise's constructor creates a new promise, initially in the pending state. It calls `e` (the executeFunction function) and provides references to the resolving functions to it that can be used to change its state.
state = pending;
e(_res,_rej); //starts my op. asynchronously (a new thread). Reference to resolving functions, _res, _rej is provided. _res and _rej are Promise's internal functions (see below)
//constructor doesn't return till the async thread finishes
}
_res (value){ //Promise's internal method
//probably sets the state of promise to Fulfilled and store the result of the Promise
state = fulfilled
resolvedValue = value;
}
_rej {//Promise's internal method
probably sets the state of promise to Rejected and store the result of the Promise
state = rejected
resolvedValue = error;
}
创建Promise
开始异步执行代码。 现在我们有兴趣知道executeFunction
的结果是executeFunction
(我们不关心executeFunction
结束)。 为此,我们调用then
的Promise
p
。 then
接受两个可选参数并将它们注册为回调。 我不确定何时以及谁调用这些回调。 我知道then
返回另一个Promise
但我无法理解它是如何工作的
then(executeFnIfPromiseResolved, executeFnIfPromiseRejected):Promise {
register executeFnIfPromiseResolved as callback
register executeFnIfPromiseRejected as callback
//NOT SURE WHO AND WHEN THE CALLBACKS ARE CALLED
//then needs to return Promise. What would be the executor function of that Promise?
}
我整天都在研究 Promises,并且有同样的问题。 我终于弄明白了。
当你创建一个 Promise 对象时,你给 Promise Constructor 一个executor
,它可以是任何函数,只要它有这个签名。
anyFunction(resolutionFunction, rejectionFunction){
// typically, some asynchronous operation.
}
因此,可以使用任何具有 2 个函数作为参数的函数。 第一个函数是你在它工作时调用的函数,第二个是你在它中断时调用的函数。 您也可以随意命名这些函数。
Promise 构造函数接受你传入的函数并用它做一些事情。
现在在你的 executor 函数中,当 promise 解决时,你调用 positionally first 函数并传递一个值。 它看起来像:
resolutionFunction(value)
您可能想知道, resolutionFunction
是在哪里定义的? 请记住,Promise 构造函数为我们定义了该函数。 所以我们可以调用resolutionFunction
而不必自己定义。 在幕后,当我们调用由 Promise 构造函数生成的resolutionFunction
时,它会将 Promise 的状态设置为已完成,调用promiseObject.then
函数内部的函数,并将值传递给.then
函数以便您可以使用它。
如果承诺失败并且会发生同样的事情并且您可以处理失败,您将调用第二个位置函数。
这个关于 Promise Constructor 的 Mozilla Doc非常有帮助。
这是一个简短的示例,显示了我上面解释的内容。
function anyFunction(callThisFunctionWhenItWorks, callThisFunctionWhenItBreaks) {
let importantNumber = 10; //change to 11 if you want the promise to reject
if (importantNumber == 10) {
callThisFunctionWhenItWorks('Hooray, success, so we call resolved for the promise.');
} else {
callThisFunctionWhenItBreaks('Boo, rejected because important number is not equal to 10');
}
}
//make a new promise
const examplePromise = new Promise(anyFunction);
//use the promise
examplePromise.then(function(result) {
console.log(result);
}).catch(function (error) {
console.log(error);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.