簡體   English   中英

如何使用異步解決此錯誤?

[英]How to solve this error with async?

我從node.js開始,試圖將try..catch與文件系統方法一起使用。 這就是我所擁有的:

let fs = require("fs");
const util = require('util');

let buf = new Buffer(1024);

const open = util.promisify(fs.open);
const read = util.promisify(fs.read);
const close = util.promisify(fs.close)

async function main(){
  console.log("Going to open an existing file");
  try{
    const fd = await open('input.txt', 'r+');
    console.log("File opened successfully!");
    console.log("Going to read the file");

    try{
      await read(fd, buf, 0, buf.length, 0);
      if(bytes > 0) 
         console.log(buf.slice(0, bytes).toString());
    }
    catch(e){
      console.log("Error");
   } 
 }
 catch(e){
   console.log("Error");
 }
} 
main();
console.log("Program ended");

當我執行時,它轉到第二個捕獲,並且不打印任何內容。

在此處輸入圖片說明

使用更新的代碼,我看到的唯一錯誤是來自未聲明的bytes變量。

await read(fd, buf, 0, buf.length, 0); 將返回一個具有以下值的值:

{ 
  buffer: bufferData,
  bytesRead: numberOfBytes
} 

因此,在異步代碼中,您需要獲取它們並使用它們:

try{
  let ret = await read(fd, buf, 0, buf.length, 0);
  if(ret.bytesRead > 0) 
     console.log(buf.slice(0, ret.bytesRead).toString());
}

當然,您也可以只打印從read()返回的緩沖區。

catch塊中打印錯誤也將很有幫助:

catch(e){
  console.log("Error", e);
} 

另外,如果您希望console.log結尾在正確的時間,則應使用類似以下內容:

main().then(() => console.log("Program ended")) ;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM