From 1689c1edef805a0167e8c0f0db3a7e357d512563 Mon Sep 17 00:00:00 2001 From: morning-star <26325820+Sight-wcg@users.noreply.github.com> Date: Fri, 24 May 2024 09:16:31 +0800 Subject: [PATCH] =?UTF-8?q?feat(upload):=20before=20=E9=80=89=E9=A1=B9?= =?UTF-8?q?=E7=9A=84=E8=BF=94=E5=9B=9E=E5=80=BC=E6=94=AF=E6=8C=81=20Promis?= =?UTF-8?q?e=20=E5=92=8C=20Deferred=20Promise=20=E5=AF=B9=E8=B1=A1?= =?UTF-8?q?=E7=B1=BB=E5=9E=8B=20(#1919)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(upload): before 选项的返回值支持 Promise 和 Deferred Promise 对象类型 * docs(upload): 更新文档 --- docs/upload/detail/options.md | 31 +++++++++++++++++++++++++++++++ src/modules/upload.js | 33 +++++++++++++++++++++++++-------- 2 files changed, 56 insertions(+), 8 deletions(-) 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(); }; // 文件类型名称