diff --git a/docs/upload/detail/options.md b/docs/upload/detail/options.md index 79bddaf0..695bd70e 100644 --- a/docs/upload/detail/options.md +++ b/docs/upload/detail/options.md @@ -388,6 +388,37 @@ before: function(obj){ // obj 参数同 choose } */ } + +// 返回 jQuery Deferred.promise 对象或 JS 原生 Promise 对象,reject 表明阻止上传(2.9.11+) +// Promise +before: function(obj){ + return new Promise(function(resolve, reject){ + setTimeout(function(){ + console.log('before_async_task', obj); + resolve(); + }, 1000) + }) +} + +// Deferred +before: function(obj){ + return $.Deferred(function(deferred){ + setTimeout(function(){ + console.log('before_async_task', obj); + deferred.resolve(); + }, 1000) + }).promise(); +} + +// Deferred2 +before: function(obj){ + var deferred = $.Deferred(); + setTimeout(function(){ + console.log('before_async_task', obj); + deferred.resolve(); + }, 1000) + return deferred.promise(); +} ``` diff --git a/src/modules/upload.js b/src/modules/upload.js index 811d809a..9688d8e6 100644 --- a/src/modules/upload.js +++ b/src/modules/upload.js @@ -462,15 +462,32 @@ layui.define(['lay', 'layer'], function(exports){ // 提交上传 var send = function(){ - // 上传前的回调 - 如果回调函数明确返回 false,则停止上传 - if(options.before && (options.before(args) === false)) return; - - // IE 兼容处理 - if(device.ie){ - return device.ie > 9 ? ajaxSend() : iframeSend(); + var ready = function(){ + // IE 兼容处理 + if(device.ie){ + return device.ie > 9 ? ajaxSend() : iframeSend(); + } + ajaxSend(); + } + // 上传前的回调 - 如果回调函数明确返回 false 或 Promise.reject,则停止上传 + if(typeof options.before === 'function'){ + var maybePromise = options.before(args); + if(maybePromise === false){ + return; + }else if(typeof maybePromise === 'object' && typeof maybePromise.then === 'function'){ + // 兼容 jQuery Deferred Promise 对象和原生 Promise 对象 + // 类型检测不够完善,但足以满足此场景 + maybePromise.then(function(result){ + ready(); + }, function(error){ + layui.hint().error(error); + }) + }else{ + ready(); + } + }else{ + ready(); } - - ajaxSend(); }; // 文件类型名称