我正在尝试使用窗口对象在我的打字稿库中设置端点。在我的 global.ts 中,我有以下内容:
declare global {
interface Window {
DICTIONARY_ENDPOINT_URL: string;
OTHER_ENDPOINT_URL?: string;
}
}
function setDictionaryEndpointURL() {
window.DICTIONARY_ENDPOINT_URL = DISPATCHER_API_HOST + DOWNLOAD_DICTIONARY_BY_LANGUAGE_ENDPOINT;
};
setDictionaryEndpointURL();
在我的 fetchDictionary.ts 中,我有这个 fetch 调用:
function fetchDictionary(
i18n: I18n,
feature: string
): Dict | null {
const url = window.DICTIONARY_ENDPOINT_URL;
const response = fetch(url, {
method: 'GET',
});
const jsonResponse = response.ok ? response.json().content : null;
return jsonResponse;
}
URL 始终解析为未定义。
我尝试将 fetch 方法更改为异步方法,但我仍然遇到相同的问题,即 URL 未定义。
fetch
和Response
json
方法都不是同步工作的,都返回promises。但您的代码期望它们同步返回结果。
相反,创建
fetchDictionary
asyncand add the appropriate
await` 表达式。这是最小改动的版本:
async function fetchDictionary( // <== Added `async`
i18n: I18n,
feature: string
): Dict | null {
const url = window.DICTIONARY_ENDPOINT_URL;
const response = await fetch(url, { // <== Added `await`
method: 'GET',
});
const jsonResponse = response.ok ? (await response.json()).content : null;
// Added `await` ------------------^^^^^^^^^^^^^^^^^^^^^^^
return jsonResponse;
}