Javascript 使用getter绑定返回承诺对象的函数
使用javascript getter是将函数调用绑定到对象定义的一种很酷的方法。我以前曾多次使用它,但在最近的一个问题中,我想用它绑定一个函数,该函数返回一个jQuery承诺对象,该对象在$.when…$.then链中使用 似乎使用getter并不像我期望的那样有效;具体地说,$。然后,当绑定函数使用getter返回的函数定义时,它不会等待绑定函数的promise对象被解析。但是,如果没有使用getter,而我只是直接调用该函数,那么事情就会按预期进行 你知道为什么会这样吗 例如:Javascript 使用getter绑定返回承诺对象的函数,javascript,jquery,Javascript,Jquery,使用javascript getter是将函数调用绑定到对象定义的一种很酷的方法。我以前曾多次使用它,但在最近的一个问题中,我想用它绑定一个函数,该函数返回一个jQuery承诺对象,该对象在$.when…$.then链中使用 似乎使用getter并不像我期望的那样有效;具体地说,$。然后,当绑定函数使用getter返回的函数定义时,它不会等待绑定函数的promise对象被解析。但是,如果没有使用getter,而我只是直接调用该函数,那么事情就会按预期进行 你知道为什么会这样吗 例如: var m
var myObj = {
asynch1: {
a: 200,
b: 300,
get runAsynch3() {return function() {
myCustomAsynchCode3(this.a, this.b);
}
},
},
};
function myCustomAsynchCode1() {
var df = $.Deferred();
// do stuff that, when done, calls
// df.resolve();
return df.promise();
}
function myCustomAsynchCode2() {
var df = $.Deferred();
// do stuff that, when done, calls
// df.resolve();
return df.promise();
}
function myCustomAsynchCode3(val1, val2) {
var df = $.Deferred();
// do stuff that, when done, calls
// df.resolve();
return df.promise();
}
如果我打这样的电话
var that = this;
$.when(myCustomAsynchCode1()).
then(function() {
return that.myCustomAsynchCode2();
).
then(function() {
return that.myObj.runAsynch3();
});
runAsynch3在myCustomAsynchCode2解析其承诺对象之前执行
但是如果我打这样的电话
var that = this;
$.when(myCustomAsynchCode1()).
then(function() {
return that.myCustomAsynchCode2();
).
then(function() {
return myCustomAsynchCode3(that.myObj.a, that.myObj.b);
});
一切都按预期工作-承诺对象在不相互干涉的情况下解析。在一些承诺库eq.q中,有一个函数。allarrayOfPromises用于链接承诺。我没有在jQuery中使用Promissions,但是您可以检查deferred.pipe是否完成了您想要的任务?我认为从jQuery 1.8开始,pipe已经被弃用了。建议的用法是。有一种方法可以使用apply为执行提供一个承诺数组,但是当我测试它时,似乎数组对象的顺序并不一定保证它们将按照该顺序执行。我没有看过其他图书馆;只是对jQuery处理promise对象感兴趣。您希望$.whenmyCustomAsynchCode1做什么?$。当期望承诺/延期作为论据时。但是您正在传递一个函数。另外,发布测试代码,表明它没有按预期工作。如果不知道如何/何时解决这些承诺,就很难判断问题出在哪里。它可能只是测试代码中的一个bug;一接到电话,.when就得到了你提到的承诺对象。解析每个延迟的代码可以工作,因为我可以使用相同的方法调用它。当…如果我不使用getter,那么就成功地构建它。在调用中使用getter会导致问题,即调用代码的方式。