이 콜백 함수는 비동기 적으로 호출되며 그 안에있는 return
문에 의해 반환 된 값은 나중에 사용할 수 없습니다. 전체 프로세스가 동기 인 경우 다음 구조에만 작동합니다 : 사용자가 아직 클릭하지 않았기 때문에
var ret = Alertify.alert({
content: 'This is MY alert content!'
});
...하지만 Alertify.alert()
가 원하는 값을 반환하지 않습니다. 이 alert()
함수는 아무 것도 반환하지 않으며 여전히 발생해야하는 클릭의 결과를 확실히 반환 할 수 없습니다.
이 시나리오는 약속을하기에 이상적입니다. 이는 모습입니다 당신은 그렇게 할 때
var showModal = function (alert_id) {
$('body').append($html);
var $modal = $('#' + alert_id);
$modal.modal('show');
var dfd = $.Deferred(); // create a promise
$modal.on('click', '[data-alertify="cancel"]', function(){
var value = 'no';
$modal.modal('hide');
dfd.resolve(value); // instead of returning the value, resolve the promise with it
});
$modal.on('click', '[data-alertify="confirm"]', function(){
var value = 'yes';
$modal.modal('hide');
dfd.resolve(value);
});
$modal.on('hidden.bs.modal', function(){
$(this).remove();
dfd.resolve();
});
return dfd.promise(); // return the (unresolved) promise
};
지금 Alertify.alert
이 then
방법을 노출하는 약속 개체를 반환합니다, 당신은을 통과 :
먼저 약속을 반환 할 showModal
기능을 변경 콜백 :
Alertify.alert({
content: 'This is MY alert content!'
}).then(function(ret) {
alert(ret);
});
... 그게 전부입니다.
업데이트 된 내용은 fiddle입니다.
왜 'on' 콜백이 비동기 적으로 호출 되었습니까? – KAD
사용자 클릭에 의해 트리거되기 때문에 코드 실행이 이미 끝났을 때 발생합니다. – trincot
나는 약속을 다루어야한다는 것을 알고 있었고, 다른 방법이 있다면 그냥 추측했다. '$ .then()'을 사용하지 않고 변수에 값을 반환 할 수 있습니까? 예를 들어,'var ret_value = Alertify.prompt (.....);'코드가 깨끗하게 보이도록하려면? – Yuri