2017-08-30 24 views
1

我想用回調包裹我的頭繞過異步JS。在我的HTML中,我有一個按鈕和一個div區域來顯示文本。回調函數的輸出沒有被記錄(JavaScript)

<button class="btn btn-default">Fetch User</button> 
<hr> 
<div></div> 

我的JS如下:

const button = document.querySelector("button"); 
const div = document.querySelector("div"); 

const setText = (text) => { 
    div.textContent = text 
} 


const checkAuth = ca => { 
    setText('Checking Auth...') 
    setTimeout(() => { 
    ca(true); 
    }, 2000); 
}; 

const fetchUser = fu => { 
    setText('Fetching User...') 
    setTimeout(() => { 
    fu ({ name: "PENNYWISE" }) ; 
    }, 2000); 
}; 

const evilLaughter = el => { 
    setText('Red balloon drifting your way...') 
    setTimeout(() => { 
    el ({ laughter: "HA HA HA" }) ; 
    }, 2000); 
}; 

button.addEventListener("click",() => { 
    checkAuth(isauth => { 
    if (isauth) { 
     fetchUser(user => { 
     setText(user.name); 
      evilLaughter(intro => { 
       setText(intro.laughter) 
      }); 
     }); 
    } 
    }); 
}); 

我期望在FOLL序列代碼輸出: 檢查驗證 - >獲取用戶 - >錙銖必較 - >紅色氣球飄向你way - > HA HA HA

但是,代碼不是以所需的順序輸出。它輸出如下: 檢查驗證 - >獲取用戶 - >紅氣球漂流的方式 - >哈哈哈

所以我想弄明白爲什麼'PENNYWISE'不顯示。任何指導將不勝感激。

+0

它應該按照預期給出輸出,嘗試'const setText =(text)=> div.textContent + = text }'。這將concat所有輸出到你的div – Nemani

回答

2
setText(user.name); 
     evilLaughter(intro => { 
      setText(intro.laughter) 
     }); 

這導致setText("PENNYWISE")的代碼是立即隨後其導致setText("Red balloon drifting your way")的代碼。

這些陳述之間沒有延遲。

DOM得到更新,然後立即再次更新。

這太快了,無法對顯示畫面進行重新繪製,即使不是這樣,人眼看起來也太快了。

+0

得到它...喲。 'PENNYWISE'正在登錄,但沒有顯示。 setTimeout(()=> setText('Red balloon drift your way ...'),2000);' – Nosail