簡體   English   中英

所有功能完成后回調

[英]Callback after all functions done

這就是這樣的任務,挑戰,從字面上看,我概述的一切都是信息

我們可以為回調“全部完成”添加另一個參數。

重要的是,console.log('all is done') 只需要在所有 'timer' 函數完成執行后才需要顯示,而不管它們的調用順序如何。

我無法弄清楚以哪種方式來處理任務,我需要使用回調輸出,但我需要等待所有調用完成我們有:

 //Write a “timer” function which takes a function and timeout, after all executions fire a callback ('all is done'): const timer = // your code timer( () => { console.log(500) }, 500 ) timer( () => { console.log(3000) }, 3000 ) timer( () => { console.log(1500) }, 1500 ) timer( () => { console.log(2500) }, 2500 )

如果它是一個與承諾相關的問題,你的常量返回一個帶有承諾的函數:

const timer = (timeout) =>  {
  return new Promise(function(resolve, reject) {
  setTimeout(function(timeout) {
    resolve(() => { console.log(timeout)});
  }, timeout);
});
}

Promise.all().then( () => { alert("All is done") })

這就是我解決問題的方法。 在不使用全局變量的情況下解決它會很酷。

 //Write a “timer” function which takes a function and timeout, after all executions fire a callback ('all is done'): let maxTimer = 0; const timer = async (toRun, timeout) => { ++maxTimer const done = await new Promise((resolve, reject) => { setTimeout(() => { toRun() resolve() }, timeout) } ) if (maxTimer === 0){ console.log('all is done') } }// your code timer( () => { console.log(6000) --maxTimer }, 6000 ) timer( () => { console.log(500) --maxTimer }, 500 ) timer( () => { console.log(1500) --maxTimer }, 1500 ) timer( () => { console.log(7000) --maxTimer }, 7000 ) timer( () => { console.log(2500) --maxTimer }, 2500 )

暫無
暫無

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

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