Why do two asynchronous io operations affect each other?

  Kiến thức lập trình
  • node: v20.12.1
  • OS: mac

The correct code:

import fs from 'node:fs/promises'

const dir = './a/b/c'

fs.access(dir).catch((e) => {
  return fs.mkdir(dir, { recursive: true })
}).then(() => {
  fs.writeFile(`${dir}/hello2.txt`, 'Hello, World!')
})

But I would like to know why fs.writeFile execution fails after removing return, and fs.mkdir also fails.

import fs from 'node:fs/promises'

const dir = './a/b/c'

fs.access(dir).catch((e) => {
  fs.mkdir(dir, { recursive: true })
}).then(() => {
  fs.writeFile(`${dir}/hello2.txt`, 'Hello, World!')
})

LEAVE A COMMENT