我正在使用AngularJs和模块ngSweetAlert http://oitozero.github.io/ngSweetAlert/#/home,我必须等待for循环中确认按钮功能中的指令执行:
for (var i = 0; i < myArray.length; i++) {
SweetAlert.swal({
title: "Are you sure?",
text: "Your will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
}, function(isConfirm) {
if (isConfirm) {
// Instructions using myArray
} else {
}
});
}
答案 0 :(得分:1)
编辑:正如Andrew Luhring指出的那样,原始民意调查示例不正确
以下是如何使用异步回调样式在前者完成后安排每个警报弹出窗口:
function showAlertNTimes(n) {
if (n > 0) {
SweetAlert.swal({...}, function() {
// Do confirmation stuff
showAlertNTimes(n - 1);
});
}
}
showAlertNTimes(myArray.length);
答案 1 :(得分:0)
使用承诺:
var deferred = $q.defer();
q.resolve(isConfirm); // or whatever ur data is
return deferred.promise;
然后使用“then”来指定应该对返回的promise的结果做什么;
yourFn().then(function(isConfirm){
//do stuff
});
答案 2 :(得分:0)
当心,未经测试
不熟悉swal,但在快速查看它的源代码之后它似乎没有提供promises,所以我写了一个小包装器(基于src,在链接的演示页面上):
//since swal doesn't implement promises on it's own, here a wrapper that returns one
function $swal(title, message, type){
return typeof message === "function"? $swal(title).then(message):
typeof title !== "object"? $swal({ title:title, message:message, type:type }):
config => $q(function(resolve){ window.swal(config, resolve) });
}
这应该像常规的swap函数一样,只是返回一个promise。需要$q
来自angular和初始化的SweetAlert
现在asyncromity变得简单了:
myArray.reduce(function(prev, value, index, arr){
//wait till the previous promise has been resolved,
//then resolve the this one
return prev.then(function(){
//return prev.catch(/* error handling for prev */).then(function(){
//utilize the wrapped function.
return $swal({
title: "Are you sure?",
text: "Your will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
//}).then(function(isConfirm){
}, function(isConfirm){ //this is just an alias for the previous line
console.log(index, isConfirm, value);
});
});
}, $q.resolve(true));
我传递了一个已经解决的Promise,所以我没有必要处理它是第一个还是一个从属的电话。
reduce也包含每次调用的当前索引和值。
尚未处理的一件事是,如果您的代码抛出错误。
编辑:正如4castle在评论中指出的,SweetAlert2似乎实施了承诺。
那么,你根本就不需要$ swal-wrapper,并使用带有reduce的常规swal函数。