[英]JavaScript, Node.JS : Wait until copying a folder, then edit files in it (async, await)
我正在構建一個 node.js 程序,該程序復制一個目錄,然后編輯其中的文件。 但是,我的代碼嘗試在復制完成之前編輯文件。 我嘗試在代碼中添加await
,但無法解決問題。 以下是我的代碼。
const srcDir = `./old_dir`
const destDir = `./new_dir`
await fse.copy(srcDir, destDir, function (err) {
if (err) throw err
})
// call the function that edits the files
await create_page({info: queryparams})
我想等到復制目錄完成,然后調用create_page。 但是,下面的代碼在復制目錄之前調用了create_page,導致“沒有這樣的文件或目錄”的錯誤。
來自fs-extra的文檔:
如果回調未通過,所有異步方法都將返回一個承諾。
由於您將回調傳遞給copy
方法,因此await
不會“等待”異步操作完成。 所以刪除回調參數:
const srcDir = `./old_dir`
const destDir = `./new_dir`
await fse.copy(srcDir, destDir);
// call the function that edits the files
await create_page({info: queryparams})
如果您除了在錯誤發生時重新拋出錯誤之外還想要其他任何東西,請將await
代碼包裝在try...catch
塊中。
添加 @trincot 答案的替代方法,您還可以使用copySync(src, dest[, options])
方法,等待任務完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.