feat(upload): before 选项的返回值支持 Promise 和 Deferred Promise 对象类型 (#1919)

* feat(upload): before 选项的返回值支持 Promise 和 Deferred Promise 对象类型

* docs(upload): 更新文档
pull/1950/head
morning-star 6 months ago committed by GitHub
parent c15d4e6bbc
commit 1689c1edef
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -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();
}
```
</td>

@ -462,15 +462,32 @@ layui.define(['lay', 'layer'], function(exports){
// 提交上传
var send = function(){
// 上传前的回调 - 如果回调函数明确返回 false则停止上传
if(options.before && (options.before(args) === false)) return;
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();
}
};
// 文件类型名称

Loading…
Cancel
Save