簡體   English   中英

在不修改 setTimeout 的情況下隨機延遲按順序打印數字

[英]Print numbers in order with random delay without modifying setTimeout

function getNum(value, callback){

    setTimeout(()=> {
        callback(value)
    }, Math.random()*1000)
}

 function getNumList(arr, callback){
    //complete this function
    //use the given "getNum" function
    //(not allowed to use Math.sqrt function)
    //(not allowed to use setTimeout function)
   for(let i=0; i<arr.length;i++)
   getNum(arr[i],callback)
 }

getNumList([1,3,2,4,6,5,7,9,8,10], (nums)=> console.log(nums))
//should print [1,3,2,4,6,5,7,9,8,10] in console

如何通過只修改getNumList 來解決這個問題? 對於遞歸或承諾,我將不得不根據我的理解修改 getNum function。 有辦法解決這個問題嗎?

您可以使用 promise 包裝對getRoot的調用,並將_ => res(callback(_))作為回調傳遞給getRoot

 function getRoot(value, callback) { setTimeout(() => { const root = Math.sqrt(value) callback(root) }, Math.random() * 1000) } async function getRootList(arr, callback) { for (let i = 0; i < arr.length; i++) { await new Promise((res) => getRoot(arr[i], (...args) => res(callback(...args))) ) } } getRootList([1, 9, 4, 16, 36, 25, 49, 81, 64, 100], (roots) => console.log(roots))

筆記:

  • (...args)部分在您的情況下不是必需的。 但是,如果回調有多個 arguments,那是必需的。
  • 如果console.log不是回調的一部分,則將回調值傳遞給res很有用。 這樣,您就可以在循環內獲取回調返回的值。 這是回調具有邏輯的示例:

 function getRoot(value, callback) { setTimeout(callback, Math.random() * 1000, value) } async function getRootList(arr, callback) { for (let i = 0; i < arr.length; i++) { const value = await new Promise((res) => getRoot(arr[i], (...args) => res(callback(...args))) ) console.log(value) } } getRootList([1, 9, 4, 16, 36, 25, 49, 81, 64, 100], Math.sqrt) // getRootList([1, 9, 4, 16, 36, 25, 49, 81, 64, 100], (a, pow = 2) => Math.pow(a, pow))

我不是 100% 確定這里的最終目標是什么。 有很多方法,但沒有一種是完全有意義的(因為結束回調接收roots prop)。 如果它是關於行使遞歸,那么這將有助於:

// not modified
function getRoot(value, callback){
    setTimeout(()=> {
        const root = Math.sqrt(value)
        callback(root)
    }, Math.random()*1000)
    // console.log()
}

 function getRootList(arr, callback){
    if (!arr.length) { // a way to stop the recursion
        return;
    }
    getRoot(arr[0], (rt) => { // get the root for the first element of the array
      callback(rt); // print it
      getRootList(arr.slice(1), callback); // start recursion, stripping the 1st element
    });
 }

getRootList([1,9,4,16,36,25,49,81,64,100], (roots)=> console.log(roots))
//should print [1,3,2,4,6,5,7,9,8,10] in console

暫無
暫無

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

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