想象一下,我有X
,Y
和Z
函数,所有函数都返回并准备好链接。我想要做的是在完成并处理错误后通知进度。什么是更好的写和为什么(有什么后果):如何从JavaScript函数返回承诺?
A.
function my_func(index, size){
return X
.then(Y)
.then(Z)
.then(
function(data){
var dfd = new $.Deferred();
dfd.notify("progress", index/size, 'OK');
dfd.resolve(data);
return dfd.promise();
},
function(){
return handleError(arguments, size, index);
}
);
}
或
B.
function my_func(index, size){
var dfd = new $.Deferred();
X
.then(Y)
.then(Z)
.then(
function(data){
dfd.notify("progress", index/size, 'OK');
dfd.resolve(data);
},
function(){
return handleError(arguments, size, index);
}
)
return dfd.promise();
}
此外,之间有什么区别:
X.then(Y).then(Z);
和:
$.when(X).then(Y).than(Z);
如果$.when
一部分是不必要的,为什么doeas它在jQuery的存在呢?
评论从@Benjamin Gruenbaum评论中删除。 –
你说得对。对不起! –