var globalData = null;
$.post('/api/data', function(res) {
globalData = res; // 回調內賦值
});
console.log(globalData); // null!AJAX 尚未完成
$.post 發起非同步請求 (宏任務)。console.log。globalData = res。**結論**:非同步代碼的「後續邏輯」必須寫在回調/Promise/await 內部,而非外部同步代碼區塊。
// 全域設定 (影響所有 AJAX)
$.ajaxSetup({ async: false });
// 或單次
$.ajax({ url: '/api/data', async: false, success: function(res) { globalData = res; } });
嚴重缺點:凍結瀏覽器 UI、違反 HTML 標準、Chrome 控制台紅字警告、無法取消、錯誤處理困難。**生產環境嚴禁使用。**
// 回調模式
function fetchData(callback) {
$.post('/api/data', function(res) {
callback(res);
});
}
fetchData(function(data) {
globalData = data;
renderUI(data); // 後續邏輯在這裡
});
// 或事件模式 (jQuery)
$(document).on('dataLoaded', function(e, data) {
globalData = data;
});
$.post('/api/data', function(res) {
$(document).trigger('dataLoaded', res);
});
// 1. 封裝為回傳 Promise 的函數
function fetchData() {
// $.ajax 回傳 jqXHR,實作 Promise 介面
return $.ajax({
url: '/api/data',
method: 'GET',
dataType: 'json'
});
}
// 2. async/await 使用 (需在 async 函數中)
async function initPage() {
try {
var data = await fetchData(); // 這裡「暫停」等待,不阻塞主執行緒
globalData = data; // 確實拿到資料後才執行
renderUI(data);
} catch (err) {
console.error('載入失敗', err);
showError('資料載入失敗,請重試');
}
}
initPage();
// 並行:同時發送,全部完成才繼續
async function loadDashboard() {
var [user, notifications, settings] = await Promise.all([
fetchData('/api/user'),
fetchData('/api/notifications'),
fetchData('/api/settings')
]);
// 三個都拿到才執行這裡
renderDashboard(user, notifications, settings);
}
// 競速:最快回應者勝出 (超時控制)
function fetchWithTimeout(url, ms = 5000) {
return Promise.race([
$.ajax(url),
new Promise((_, reject) => setTimeout(() => reject(new Error('Timeout')), ms))
]);
}
// 串序:前一個完成才發下一個 (如需依賴前一個結果)
async function sequential() {
var step1 = await fetchData('/api/step1');
var step2 = await fetchData('/api/step2?id=' + step1.id);
return step2;
}
全域變數污染全域命名空間、難以追蹤變更、不利測試。現代架構建議:
// stores/data.js
export const useDataStore = defineStore('data', {
state: () => ({ items: [], loading: false, error: null }),
actions: {
async load() {
this.loading = true;
try {
this.items = await fetchData('/api/items');
} catch (e) {
this.error = e.message;
} finally {
this.loading = false;
}
}
}
});
// Component.vue
const store = useDataStore();
await store.load();
// store.items 為響應式,模板自動更新
// store.js (Zustand 極簡)
import { create } from 'zustand';
export const useDataStore = create((set) => ({
items: [],
load: async () => {
set({ loading: true });
try {
const items = await fetchData('/api/items');
set({ items, loading: false });
} catch (e) {
set({ error: e.message, loading: false });
}
}
}));
// Component
const { items, load } = useDataStore();
useEffect(() => { load(); }, []);
core-js / regenerator-runtime Polyfill (支援 async/await 於舊瀏覽器)。$.ajax 封裝為回傳 Promise 的服務函數 (api.js)。async/await 線性流程。State 物件 + EventTarget 發布變更) 替代全域變數。async: false:破壞使用者體驗、違反標準。