简体   繁体   English

如何同步从Google云端硬盘下载文件?

[英]How to download files from Google Drive synchronously?

还是有办法产生相同的效果,即JavaScript程序停止直到下载完成(不使用setTimeout )?

Javascript is asynchronous, so you need to handle the download asynchronously. Javascript是异步的,因此您需要异步处理下载。 This is mainly because javascript runs single threaded and that's generally shared with the UI thread, so if you blocked your code on a download the user wouldn't be able to interact with the page at all until your code finished. 这主要是因为javascript运行单线程,并且通常与UI线程共享,因此,如果您在下载中阻止了代码,则在代码完成之前,用户将无法与页面进行交互。

However, handling it asynchronously shouldn't be difficult, so long as the mechanism you're using to download the file supports a callback when it's done (which most should). 但是,异步处理并不难,只要您用来下载文件的机制在完成后就支持回调(多数情况下应该如此)。

Say you had the following code: 假设您有以下代码:

function doDownload(url) {
  doSomeInitialStuff();
  startDownload(url);  // assuming this would block, which it can't
  doSomeOtherStuff();
  doMoreOtherStuff();
}

If your download mechanism supports a callback when it's done (a function that's called after the download is complete or has failed), then you would restructure your code like so: 如果您的下载机制完成后支持回调(在下载完成或失败后调用的函数),那么您将按照以下方式重组代码:

function doDownload(url) {
  doSomeInitialStuff();
  startDownload(url, onDownloadComplete);
}

function onDownloadComplete() {
  doSomeOtherStuff();
  doMoreOtherStuff();
}

The specifics of how you callback works (args passed to it, how it's provided to the download code) will vary depending on the js libraries you're using, but this is the basic idea for how to handle it asynchronously. 回调工作方式的具体细节(传递给它的参数,如何将其提供给下载代码)将根据您使用的js库而有所不同,但这是如何异步处理它的基本思想。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM