简体   繁体   English

有没有更简单的方法来暂停执行然后在异步 function 上进行回调?

[英]Is there an easier way to pause execution then a callback on an async function?

I have a nodejs application where I download a file which is then immediately used and the rest of the program depends on that file being used, the only problem is that the only function I have to download the file through Google Cloud is asynchronous which means in order to stop the program from immediately crashing when it realizes the file hasn't been fully downloaded is to stick a callback on my asyncronous function for downloading.我有一个 nodejs 应用程序,我在其中下载了一个文件,然后立即使用该文件,程序的 rest 取决于正在使用的文件,唯一的问题是我必须通过 Google Cloud 下载文件的唯一 function 是异步的,这意味着为了阻止程序在意识到文件尚未完全下载时立即崩溃,请在我的异步 function 上进行回调以进行下载。

This would normally be fine, but unfortunately the rest of the program is around 400 LINES LONG which means a 400 LINE LONG CALLBACK FUNCTION.这通常没问题,但不幸的是,程序的 rest 大约 400 LINES LONG,这意味着 400 LINE LONG 回调 FUNCTION。 Which is understandably ugly.这是可以理解的丑陋。

If anyone can tell me of a simpler method for pausing execution than this callback function, I would appreciate it.如果有人能告诉我比这个回调 function 更简单的暂停执行方法,我将不胜感激。

Feel free to let me know if this is a duplicate question and this exact one has been answered elsewhere.如果这是一个重复的问题,并且这个确切的问题已在其他地方得到回答,请随时告诉我。 I scoured for this question myself, but couldn't find it.我自己搜索了这个问题,但找不到。

 async function downloader(callback){ await download(file); //insert download function here callback(); } downloader(function(){ var usefulthing = JSON.parse(file); //Insert 400 lines of code here });

You can separate your 400 lines of code into a file and export a function, let say named handleFile .您可以将 400 行代码分成一个文件并导出一个 function,比如说命名为handleFile Then in your callback function just call:然后在您的回调 function 中调用:

downloader(function(){
  var usefulthing = JSON.parse(file);
  handleFile(file)
});
const Downloader=async()=>{

   const file = await download(file)
    // this now returns the file as a promise 
   return file 
}
function MainStuff async(){
   const file =await Downloader()
  // the 400 lines of code now will wait this file to finish downloading
}

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

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