简体   繁体   English

在这种情况下,为什么不尝试并抓住工作呢?

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

I'm learning Node.js but cannot understand why this is not working. 我正在学习Node.js,但无法理解为什么它不起作用。 What is the problem? 问题是什么? Thanks for an answer. 感谢您的回答。

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')
}

This is the result: 结果如下:

Error: EEXIST: file already exists, mkdir 'c:\\Users\\stefa\\Desktop\\programming\\learning-node\\playground\\paths\\test' 错误:EEXIST:文件已存在,mkdir'c:\\ Users \\ stefa \\ Desktop \\ programming \\ learning-node \\ playground \\ paths \\ test'

Callback created by lambda expression of err => {/**/} is ran asynchronously. err => {/**/}的lambda表达式创建的回调是异步运行的。 try-catch cannot catch that. try-catch无法捕捉到。

You should use Promise s/ Future s or synchronized version of fs.mkdir function, fs.mkdirSync . 您应该使用PromiseFuturefs.mkdir函数的同步版本fs.mkdirSync

Try something like this: 尝试这样的事情:

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

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

or 要么

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')
    }
}());

As PsychoX said, the callback is called asynchronously . 正如PsychoX所说,回调是异步调用的。

You have a few choices: 您有几种选择:

  1. Just use the callback 只需使用回调

  2. Use the promises-based fs API (or use util.promisify on mkdir , but...) 使用基于 util.promisify 的fs API (或在mkdir上使用util.promisify ,但是...)

  3. (Not recommended) Use the Sync versoin of mkdir ( mkdirSync ) (不推荐)使用Sync versoin of mkdirmkdirSync

Here's #1: 这是#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
})

Here's #2, using fsPromises.mkdir : #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')
})

or within an async function: 或在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