同步下载文本文件JavaScript



我正在制作一个非常轻量级的网页,它下载一个文件,然后显示基于该文件的内容。没有文件就没有显示的内容,我也没有扩大这个网页的计划。除非万不得已,否则我不想使用异步方法。

如何下载一个文件,使JavaScript在下载文件之前暂停。

只需将整个脚本封装在异步IIFE中,然后等待单个网络请求:

// immediately invoked async function expression:
(async () => {
// all of your sync code before the fetch request to get the file
const response = await fetch(url);
// handle response, parse data, etc.
// all of the rest of your sync code after the fetch request,
// which won't execute until after the fetch promise is
// resolved as the response (or rejected)
})();

最新更新