1

I have the following code on a server:

let tmpFileName;

// GET
app.get('/clicked', async (req, res) => {
    let nullOutput = writeTmpFile("hello, world!");
    await deleteTmpFile();
    console.log("Hurray, finished!");
    res.send({result:nullOutput});
})

function writeTmpFile(content){
    tmpFileName = "tmp" + Math.random().toString() + "tsl";
    return new Promise(resolve => {
        fs.writeFile(tmpFileName, content, function (err) {
            if (err) throw err;
            console.log('Temp file creation successful.');
        });
    })
}

function deleteTmpFile(spec){
    return new Promise(resolve => {
        fs.unlink(tmpFileName, function (err) {
            if (err) throw err;
            console.log('Temp file deletion successful.');
        });
    })
}

However, in my console output, I only get

Temp file creation successful.
Temp file deletion successful.

However, if I delete await deleteTempFile(), then Hurray, finished! shows up on the console.

And more generally, how do I debug these patterns of problems? Why is this happening?

Alex Coleman
  • 607
  • 1
  • 4
  • 11

2 Answers2

0

I have rewritten your code, to showcase how to use promises.

Promise callback gets two functions as arguments: resolve and reject.

You should call resolve when operation finishes with success, and reject when it fails.

// I moved `tmpFileName` variable from here into the request handler,
// because it was "global" and would be shared between requests.

app.get('/clicked', async (req, res) => {
  let tmpFileName = "tmp" + Math.random().toString() + "tsl"
  let writingResult = await writeTmpFile(tmpFileName, "hello, world!")
  let deletionResult = await deleteTmpFile(tmpFileName)
  res.send({ writingResult, deletionResult })
  console.log("Hurray, finished!")
})

function writeTmpFile (filename, content) {
  return new Promise((resolve, reject) => {
    fs.writeFile(filename, content, function (err) {
      // on error reject promise with value of your choice
      if (err) reject(err)
      // on success resolve promise with value of your choice
      resolve('Temp file creation successful.')
    })
  })
}

function deleteTmpFile (filename) {
  return new Promise((resolve, reject) => {
    fs.unlink(filename, function (err) {
      if (err) reject(err)
      resolve('Temp file deletion successful.')
    })
  })
}
Anastazy
  • 4,624
  • 2
  • 13
  • 22
-1
  1. For working with the file you can use writeFileSync instead writeFile. (Reference).

  2. For multiple Promise you can use the Promise.all method.

const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then((values) => {
  console.log(values);
});

from MDN

double-beep
  • 5,031
  • 17
  • 33
  • 41
hamidreza nikoonia
  • 2,007
  • 20
  • 28
  • 1
    Using `writeFileSync` for a code running in a request handler will block event loop until writing finishes. – Anastazy Dec 25 '20 at 12:42