Skip to content

Instantly share code, notes, and snippets.

@gmantri
Created March 23, 2018 01:37
Show Gist options
  • Save gmantri/e68ac10890df58ef46ed51eec34b45a3 to your computer and use it in GitHub Desktop.
Save gmantri/e68ac10890df58ef46ed51eec34b45a3 to your computer and use it in GitHub Desktop.
const fs = require('fs');
const Promise = require('bluebird');
const createEmptyFileOfSize = (fileName, size) => {
return new Promise((resolve, reject) => {
try {
fd = fs.openSync(fileName, 'w');
fs.writeSync(fd, Buffer.alloc(1), 0, 1, Math.max(0, size-1));
fs.closeSync(fd);
resolve(true);
} catch (error) {
reject(error);
}
});
};
@axiac
Copy link

axiac commented Mar 23, 2018

Since you create a Promise, the executor function passed to the Promise constructor should end as soon as possible (it is called by the Promise constructor).
The Promise constructor should complete immediately, leaving the Promise in the pending state. The Promise will complete its assignment asynchronously and change its status by calling the provided resolve or reject callbacks.

Use setTimeout(..., 0) to postpone the execution of the try/catch block after the completion of the current JavaScript event loop.

const fs = require('fs');
const Promise = require('bluebird');

const createEmptyFileOfSize = (fileName, size) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
        try {
          fd = fs.openSync(fileName, 'w');
          fs.writeSync(fd, Buffer.alloc(1), 0, 1, Math.max(0, size-1));
          fs.closeSync(fd);
          resolve(true);
        } catch (error) {
          reject(error);
        }
    }, 0)
  });
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment