简体   繁体   English

我如何按顺序执行异步代码?

[英]how i can execute async code in sequence?

    await fs.mkdir(path.join(__dirname, "/smartsheet_download"), 
   { recursive: true }, (err) => { 
     if (err) { 
       return console.error(err); 
     } 
     __dirname= path.join(__dirname, "/smartsheet_download");
   console.log("after func:" + __dirname);
   })

   console.log("this must be printed after path at last")
}

my question in this above function is i am printing "this must be printed after path at last" after the fs.mkdir operation but when i am running the code it prints first.我在上面 function 中的问题是我在 fs.mkdir 操作之后打印“这必须在最后打印路径之后”,但是当我运行它首先打印的代码时。 i am using async and await so that it must wait for fs.mkdir to complete the execution before printing the last line.我正在使用异步和等待,因此它必须等待 fs.mkdir 在打印最后一行之前完成执行。 Still this thing does not work.这个东西还是不行。 Could u please tell how can i wait for fs.mkdir to complete and then pass the execution to next line.你能告诉我如何等待 fs.mkdir 完成然后将执行传递到下一行。 moreover, please tell why await do not work here?此外,请告诉为什么 await 在这里不起作用?

your logic is correct.你的逻辑是正确的。 however, if you look at the signature of fs.mikdir it returns void但是,如果您查看fs.mikdir的签名,它会返回 void

export function mkdir(path: PathLike, options: MakeDirectoryOptions & { recursive: true }, callback: (err: NodeJS.ErrnoException | null, path: string) => void): void; <---

which means, it cannot be await ed, although it executes an async task, but due it returns void, it cannot be awaited.这意味着,它不能被await ed,虽然它执行一个异步任务,但由于它返回 void,它不能被等待。

the callback exists for when you need to know if the what happend to the operation, succesed/faild something like that, thats why your log happens before, because mkdir returns void.当您需要知道操作发生了什么,成功/失败类似的事情时,回调存在,这就是您的日志之前发生的原因,因为 mkdir 返回 void。

so if you need do something after fs.mikdir was finished.所以如果你需要在fs.mikdir完成后做一些事情。 you can use fs.mkdirSync which will block execution of code untill the call has finsished, or just do your work in the callback you pass to the function您可以使用fs.mkdirSync它将阻止代码的执行,直到调用完成,或者只是在您传递给 function 的回调中完成您的工作

fs.mkdir(path.join(__dirname, "/smartsheet_download"), 
   { recursive: true }, (err) => { 
     if (err) { 
       return console.error(err); 
     } 
     __dirname= path.join(__dirname, "/smartsheet_download");
   console.log("after func:" + __dirname);

 console.log("this must be printed after path at last")
   })



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

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