如何链接jquery Deferreds

时间:2013-06-26 09:02:35

标签: jquery jquery-deferred

假设我有以下延迟设置:

var dfr = new Deferred()

dfr.done(step1)
.then(step2)
.then(step3)

有没有办法将step2的结果传递给step3

2 个答案:

答案 0 :(得分:1)

假设step1step2step3是javascript函数,那么只需让step2返回其结果,它就会自动成为传递给{{1}的参数}。

答案 1 :(得分:1)

是的,你可以传递结果.lets看到一个下载文件的例子,这样你就可以清楚了。

 fun5().then(
            function (msg) {
            if(msg==='m1'){
            var dfd1 = $.Deferred(function (dfd1){
             //alert("called2");

            var remoteFile = "http://www.freegreatdesign.com/files/images/6/2921-large-apple-icon-png-3.jpg";
            var localFileName = remoteFile.substring(remoteFile.lastIndexOf('/')+1);
            window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
            fileSystem.root.getFile(localFileName, {create: true, exclusive: false}, function(fileEntry) {
            var localPath = fileEntry.fullPath;
            if (device.platform === "Android" && localPath.indexOf("file://") === 0) {
            localPath = localPath.substring(7);
            }

            var ft = new FileTransfer();
            ft.download(remoteFile, localPath, function(entry) {
            dfd1.resolve('m2');
            // Do what you want with successful file downloaded and then
            // call the method again to get the next file
            //downloadFile();
            }, fail);
            }, fail);
            }, fail);

            //alert("In 2");
            });

            }
            return dfd1.promise();
            }).then(
            function (msg) {
            if(msg==='m2'){
            var dfd2 = $.Deferred(function (dfd2){
             //alert("called3");

            var remoteFile = "http://www.freegreatdesign.com/files/images/6/2921-large-apple-icon-png-3.jpg";
            var localFileName = remoteFile.substring(remoteFile.lastIndexOf('/')+1);
            window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
            fileSystem.root.getFile(localFileName, {create: true, exclusive: false}, function(fileEntry) {
            var localPath = fileEntry.fullPath;
            if (device.platform === "Android" && localPath.indexOf("file://") === 0) {
            localPath = localPath.substring(7);
            }

            var ft = new FileTransfer();
            ft.download(remoteFile, localPath, function(entry) {
            dfd2.resolve('m3');
            // Do what you want with successful file downloaded and then
            // call the method again to get the next file
            //downloadFile();
            }, fail);
            }, fail);
            }, fail);

            //alert("In 3");
            });

            }
            return dfd2.promise();
            })