【发布时间】:2018-01-27 16:23:25
【问题描述】:
我正在尝试使我的网络应用程序对用户更加友好,我希望它在实际被删除之前消失,而不是立即删除一个元素。问题是我的代码运行得太快了。虽然我知道一切正常,但我需要它等待元素“消失”,然后才能真正被删除。这是什么时候使用Promise 还是我应该使用setTimeout() 的一个很好的例子?
代码概览
check if variables exist
if button is clicked change element opacity (transition: opacity 1s;)
then call deletePostPromise()
then remove the element from the dom
如你所见,我什至将我的伪代码写成一个承诺,then.. then..。
具体来说,从row.style.opacity = '0';开始
if (displayPostWrapper && submitPostBtn) {
displayPostWrapper.addEventListener('click', e => {
if (e.target && e.target.nodeName == 'BUTTON') {
e.preventDefault();
const { parentElement } = e.target;
const row = parentElement.parentElement.parentElement;
const form = parentElement;
const postID = parentElement.childNodes[3].value;;
row.style.opacity = '0';
deletePostPromise('http://localhost/mouthblog/ajax/delete_post.ajax.php', `id=${postID}`)
.then(() => {
row.remove();
});
// row.remove();
} // if
}); // click event
编辑
JS
const deletePostPromise = (url, postID) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = () => {
if (xhr.status == 200) {
console.log('if (xhr.status == 200)');
resolve();
} else {
reject(xhr.statusText);
}
};
xhr.onerror = () => {
reject(xhr.statusText);
};
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(postID);
});
}
if (displayPostWrapper && submitPostBtn) {
displayPostWrapper.addEventListener('click', e => {
if (e.target && e.target.nodeName == 'BUTTON') {
e.preventDefault();
const { parentElement } = e.target;
const row = parentElement.parentElement.parentElement;
const form = parentElement;
const postID = parentElement.childNodes[3].value;;
row.style.opacity = '0';
deletePostPromise('http://localhost/mouthblog/ajax/delete_post.ajax.php', `id=${postID}`);
row.addEventListener("transitionend", function(event) {
// alert('Done!');
row.remove();
}, false);
} // if
}); // click event
CSS
.row {
opacity: 1;
transition: opacity 5s;
}
【问题讨论】:
-
在这里使用没有
setTimeout的承诺是毫无意义的。如果要等待 1s,请使用超时。 -
为什么不立即执行 ajax 请求呢?只是不要在第二个时间过去之前从 DOM 中删除元素。
-
@jfriend00 你的意思只是一个简单的
if声明? -
@Bergi 我想我不明白,
using promises without setTimeout is pointless?我得到了第二部分。 -
你在问你是否会使用承诺或
setTimeout。我的意思是说你会同时使用。
标签: javascript asynchronous promise settimeout