Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
696 views
in Technique[技术] by (71.8m points)

promise - AngularJS $q. Deferred queue

I have array (f.e. it is queue of files):

[{deferred: fileDef, data: file}, {...}, ...]

Each fileDef and file send to upload function which return fileDef.promise and call fileDef.resolve or fileDef.reject after uploading.

I want upload files in order: next file upload after previous file is loaded.

Now I use

var queue = [];
var uploading = false;

//file input callback call each time the user selects files
function addAndUpload (file) {

  queue.push({deferred: $q.defer(), data: file});

  if (!uploading) recurceQueue();

  function recurceQueue () {
    if (queue.length) {
      uploading = true;
      var fileObj = queue.shift();
      upload(fileObj.deferred, fileObj.data);

      fileObj.deferred.promise.finally(function () {
        uploading = false;
        recurceQueue();
      })
    }
  }
}

But it seems bad. How to write better?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Don't use a queue and that boolean flag, just have one variable storing a promise representing all uploads. Also, your upload function should not take a Deferred object to resolve as an argument, but simply return a new promise.

Then the addAnUpload becomes as simple as

var allUploads = $q.when(); // init with resolved promise

function AddAnUpload(file) {
    allUploads = allUploads.then(function() {
        return upload(file);
    });
}

With the closure, you don't need that queue to store the waiting uploads any more. If you want allUploads to fulfill always, even if one upload fails, you need to return an always-fulfilling promise from the then-callback:

        return upload(file).then(null, function(err) {
            console.log(err, "does not matter");
        }); // fulfills with undefined in error case

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...