【发布时间】:2014-08-27 07:29:44
【问题描述】:
下面的代码没有按预期工作。这里的 GetAllFileNames 是异步函数,我想根据这个函数的结果执行一些顺序操作。所以我正在使用 Jquery 承诺。但我觉得语句 return deferred.resolve(GetAllFileNames) 不正确。它立即调用 promise.then 甚至不等待 GatAllFileNames 完成。请注意这实际上不是工作代码。
function getfilenames() {
var deferred = $.Deferred();
if(condition == true) {
return deferred.resolve(JSON.parse(allFileNames));
} else {
return deferred.resolve(GetAllFileNames());
}
}
var promise = getfilenames();
promise.then(function(fileNames) {
result.fileNames = fileNames;
});
更新:我尝试了你的一些 cmets,但它们都没有工作。这是一个不工作的例子
<!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> $(function () {
var deferred = $.Deferred();
var result = {};
var GetAllFileNames = function () {
return {
"allFileNames": [1, 2, 3, 4, 5, 6, 7, 8, 9]
};
};
function getfilenames(condition) {
if (condition == true) {
return deferred.notify(JSON.parse(allFileNames));
} else {
return deferred.notify(GetAllFileNames());
}
};
deferred.then(
// `deferred.done`
function (fileNames) {
result.fileNames = fileNames;
$("<span>" + result.fileNames.allFileNames + "</span>")
.appendTo("body"); console.log(JSON.stringify(fileNames));
}
// `deferred.fail`
,
function () {
console.log(new Error("getfilenames error").message);
} );
getfilenames(false);
}) </script> </head> <body>
</body> </html>
【问题讨论】:
-
确认
GetAllFileNames()是否完整的方法是什么?是否有要查询的项目的length属性?如果任务要在GetAllFileNames()之后执行,可以使用deferred.notify提供GetAllFileNames()和deferred.progress的通知,然后resolvedeferred在progress内完成时;然后调用deferred.then -
只做
function getfilenames() { return condition ? $.when(JSON.parse(allFileNames)) : GetAllFileNames(); }为什么这么麻烦?为什么要延期?为什么要下决心?这是做一些简单的事情的一种非常混乱的方式。 -
@Alien01 不确定
if语句的逻辑? ,condition是什么? ,或者getallfilenames的预期返回值是多少?由condition组成false;不确定getallfilenames可能的返回值;allFileNames是什么,如果在getallfilenames内通过函数返回?见帖子 -
@BenjaminGruenbaum 不错!另见
$.when(condition ? getfilenames() : GetAllFileNames()) -
@guest271314 更好(并且更接近我通常所做的):) 您应该编辑您的答案以摆脱 deferred anti pattern