簡體   English   中英

在這種情況下,為什么不嘗試並抓住工作呢?

[英]Why doesn't this try and catch work in this case?

我正在學習Node.js,但無法理解為什么它不起作用。 問題是什么? 感謝您的回答。

const fs = require('fs')
const path = require('path')

try {
    fs.mkdir(path.join(__dirname, '/test'), {}, err => {
    console.log(err)
    if (err) throw err
    })
}
catch (err) {
    console.log('file is already created')
}

結果如下:

錯誤:EEXIST:文件已存在,mkdir'c:\\ Users \\ stefa \\ Desktop \\ programming \\ learning-node \\ playground \\ paths \\ test'

err => {/**/}的lambda表達式創建的回調是異步運行的。 try-catch無法捕捉到。

您應該使用PromiseFuturefs.mkdir函數的同步版本fs.mkdirSync

嘗試這樣的事情:

const fs = require('fs')
const path = require('path')

try {
    fs.mkdirSync(path.join(__dirname, '/test'));
}
catch (err) {
    console.log('file is already created')
}

要么

const fs = require('fs');
const path = require('path');
const util = require('util');
const mkdirPromisifed = util.promisify(fs.mkdir);

(async() {
    // ... all other code also should be written in async manner ...
    try {
        await mkdirPromisifed(path.join(__dirname, '/test'));
    }
    catch (err) {
        console.log('file is already created')
    }
}());

正如PsychoX所說,回調是異步調用的。

您有幾種選擇:

  1. 只需使用回調

  2. 使用基於 util.promisify 的fs API (或在mkdir上使用util.promisify ,但是...)

  3. (不推薦)使用Sync versoin of mkdirmkdirSync

這是#1:

const fs = require('fs')
const path = require('path')

fs.mkdir(path.join(__dirname, '/test'), {}, err => {
    if (err) {
       console.log('file is already created')
       return
    }
    // Do the next thing here
})

#2,使用fsPromises.mkdir

const fsp = require('fs').promises
const path = require('path')

fsp.mkdir(path.join(__dirname, '/test'))
.then(() => {
    // Do the next thing here
})
.catch(err => {
   console.log('file is already created')
})

或在async函數中:

try {
    await fsp.mkdir(path.join(__dirname, '/test'))
    // Do the next thing here
} catch (err) {
   console.log('file is already created')
}

暫無
暫無

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

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