基于 WinJS Promise 的文件上传队列 [英] WinJS Promise based file upload queue

查看:64
本文介绍了基于 WinJS Promise 的文件上传队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个将文件发送到服务器的后台上传队列.当文件被推入队列 (FIFO) 时,队列应按顺序发送文件.

I need a background upload queue that sends files to a server. The queue should send the files in sequential order as they are pushed into the queue (FIFO).

var pendingFiles = [];
var filesOperation = null;

uploadNextAsync = function(file) {
  var next;
  if (!pendingFiles.length) {
    return WinJS.Promise.as();
  }
  next = pendingFiles.shift();
  fileslogger.debug("Uploading " + next);
  return fileQuery.folder.getFileAsync(next).then(function(file) {
    return Server.sendFileAsync(file).then(function() {
      return filesOk += 1;
    }, function(error) {
      filesNok += 1;
      return logger.error(error.message, error);
    }).then(function() {
      if (pendingFiles.length) {
        return uploadNextAsync(inspection);
      }
    });
  });
};

createTaskForFile = function(file) {
  if (pendingFiles.length == 0) {
    pendingFiles = [file.name]
    filesOperation = uploadNextAsync(file);
  } else {
    pendingFiles.push(file.name);
    return filesOperation.then(function() {
      return uploadNextAsync(file);
    });
  }
};

问题

似乎有时如果连续调用 createTaskForFile 非常快,那么最终会同时上传 2 个文件.所以在 createTastForFile 函数中关于它如何使用 fileOperation.then 构造或uploadNextAsync 内部的某个地方是一个小故障?

Problem

It seems that sometimes if createTaskForFile is called very quickly in succession then 2 files end up being uploaded at the same time. So somewhere is a little glitch either in the createTastForFile function on how it uses the fileOperation.then construct or inside the uploadNextAsync does something wrong?

推荐答案

您的问题是 pendingFiles 始终为空.在 createTaskForFile 中,您可以将它设置为一个单元素数组,但立即调用 uploadNextAsync() 将其移出.我想如果您在文件上传后移动文件,您的脚本可能会起作用.

Your problem is that pendingFiles is always empty. In createTaskForFile, you would set it to an one-element array then, but immediately call uploadNextAsync() which shifts it out. I guess your script might work if you shifted the file after the file has been uploaded.

然而,你实际上并不需要这个数组.您可以将操作排队到 filesOperation,这将是一个表示所有当前文件上传的承诺.

However, you actually don't need this array. You can just queue the action to filesOperation, which would be a promise representing the upload of all current files.

var filesOperation = WinJS.Promise.as();
function createTaskForFile(file) {
  return filesOperation = filesOperation.then(function() {
    return uploadNextAsync(file);
  });
}

function uploadAsync(next) {
  fileslogger.debug("Uploading " + next.name);
  return fileQuery.folder.getFileAsync(next.name).then(function(file) {
    return Server.sendFileAsync(file);
  }).then(function() {
    return filesOk += 1;
  }, function(error) {
    filesNok += 1;
    return logger.error(error.message, error);
  });
}

这篇关于基于 WinJS Promise 的文件上传队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆