我不僅要從 jQuery 過渡,而且還要使我的代碼更精簡。當我在大型企業應用程式上作業時,正在使用的 jQuery 和 JavaScript 的數量可能會達到危機點。
我想以更好的方式開始作業并再次使用 vanilla JavaScript。我使用 KendoUI 之類的工具構建應用程式,它依賴于 jQuery 使其作業。也就是說,我想將我的其余代碼保留為普通 JavaScript,簡明高效(在適當的情況下是異步的)。
我正在嘗試使用我的 JavaScript 陳述句實作以下目標
- 找到標簽容器
- 系結事件偵聽器以在事件發生時檢查選項卡 ID
shown - 異步加載 KendoUI 網格等待它
因此,為了在速記 vanilla JavaScript 中實作這一點,我執行了以下操作。
//Find the tabs using the query selector
document.querySelector('#main-tabs')
//Add an event listener that listens for the `shown` bootstrap tab event
.addEventListener('shown.bs.tab', (e) => {
//Take the id of the tab and if the name equals "overview-tab"
//then load the grid, if it doesn't then do nothing.
(e.target.id == "overview-tab") ? load_grid_opportunities() : null;
});
好的,所以從這里我開始創建我的異步函式來加載我的網格。我創建了一個異步函式load_grid_opportunities,然后我們遇到了通用的基于 KendoUI jQuery 的小部件系結。
const load_grid_opportunities = async () => {
$('#grid_opportunities').kendoGrid({
//shortened for brevity
});
}
這是我到達的地方,因為現在我想知道,我如何在 if/else 陳述句中等待這個異步函式?我的第一直覺是await像這樣簡單地呼叫行內:
(e.target.id == "overview-tab") ? await load_grid_opportunities() : null;
然而,這并沒有奏效,因為這是一個意想不到的論點。然后我嘗試使用括號來封裝請求,但這也不起作用。
(e.target.id == "overview-tab") ? (await load_grid_opportunities()) : null;
那么,我到底如何才能等待我的功能呢?
uj5u.com熱心網友回復:
要等待您的函式,您的函式必須回傳承諾,請參閱下面的代碼。
function load_grid_opportunities() {
return new Promise((resolve, reject) => {
$('#grid_opportunities').kendoGrid({
//shortened for brevity
resolve();
});
});
}
// Now you can call your function
function async doSomething()
{
if (e.target.id == "overview-tab")
{
await load_grid_opportunities()
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/359953.html
標籤:javascript 查询 异步 剑道
上一篇:React-NativeFlatList白屏不加載資料
下一篇:用可變結構替換嵌套物件的值
