簡體   English   中英

JS Promises:為什么setTimeout回調后不能設置代碼執行?

[英]JS Promises: Why is it that you can't set code to execute after the callback of setTimeout?

我正在閱讀這篇關於 Javascript 中的 promise 鏈接的文章,並且對它說how can we do something after the avatar has finished showing and gets removed? For instance, we'd like to show a form for editing that user or something else. As of now, there's no way. how can we do something after the avatar has finished showing and gets removed? For instance, we'd like to show a form for editing that user or something else. As of now, there's no way.

圖像被刪除后我們不能做某事的原因是img.remove()不返回 promise 嗎? 還是setTimeout在其回調完成后沒有返回任何內容?

它的意思是,通過使用示例中的代碼:

setTimeout(() => img.remove(), 3000); // (*)

確切地使用該代碼,您無法檢測到圖像何時被刪除並在它發生時執行某些操作 - 它的異步刪除與外部 Promise 鏈斷開連接。

修復它的文章建議是在調用.remove()時解析構造的 Promise:

setTimeout(() => {
  img.remove();
  resolve(githubUser);
}, 3000);

或者您可以在setTimeout中放置更多代碼,以便在圖像被刪除時准確運行。

setTimeout(() => {
  img.remove();
  console.log('removed');
}, 3000);

如果您不執行上述任何一項,而使用setTimeout(() => img.remove(), 3000); , 3 秒后發生的異步動作除了刪除圖像之外什么也做不了——這通常是一個錯誤。 例如,如果您想將另一個.then鏈接到它上面,它會在圖像被刪除時運行,並且圖像需要在 3 秒后被刪除

.then(() => {
  // what logic to put in here to ensure next .then runs after 3 seconds?
  setTimeout(() => {
    img.remove();
  }, 3000);
})
.then(() => {
  console.log('image removed');
});

當在.then中時,要在延遲后運行下一個.then ,您必須從上述 .then 返回.then ,並且 Promise 必須在延遲結束后解析。

.then(() => {
  // what logic to put in here to ensure next .then runs after 3 seconds?
  return new Promise((resolve) => {
    setTimeout(() => {
      img.remove();
    }, 3000);
  });
.then(() => {
  console.log('image removed');
});

如果您不從上部.then返回 Promise ,或者如果您根本不返回任何內容,則下部.then將立即運行,只要上部.then完成,這是您不想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM