battlemidget
battlemidget

Reputation: 182

Simple promise example with bluebird and coffeescript works half the time

So I'm basically attempting to write some simple code using promises and I'm having a bit of trouble understanding why this particular code works every other time.

Promise = require('bluebird')
mkdirp = Promise.promisify(require('mkdirp'))
rm = Promise.promisify(require('rimraf'))

console.log "Preparing build directory"
rm('build')
  .then(mkdirp('build'))

This will complete successfully the first run, but the second will fail, and so on.

Here is the steps:

┌[adam@bigboi] [/dev/pts/5] [master ⚡] 
└[~/Projects/bummyjab]> time coffee index.coffee ~/Dropbox/Articles/*.md
Preparing build directory
coffee index.coffee ~/Dropbox/Articles/*.md  0.25s user 0.02s system 100% cpu 0.267 total
┌[adam@bigboi] [/dev/pts/5] [master ⚡] 
└[~/Projects/bummyjab]> stat build
  File: ‘build’
  Size: 4096       Blocks: 8          IO Block: 4096   directory
Device: 804h/2052d Inode: 17172395    Links: 2
Access: (0775/drwxrwxr-x)  Uid: ( 1000/    adam)   Gid: ( 1000/    adam)
Access: 2015-06-25 22:07:49.061331341 -0400
Modify: 2015-06-25 22:07:49.061331341 -0400
Change: 2015-06-25 22:07:49.061331341 -0400
 Birth: -
┌[adam@bigboi] [/dev/pts/5] [master ⚡] 
└[~/Projects/bummyjab]> time coffee index.coffee ~/Dropbox/Articles/*.md
Preparing build directory
Unhandled rejection Error: EEXIST: file already exists, mkdir '/home/adam/Projects/bummyjab/build'
  at Error (native)

coffee index.coffee ~/Dropbox/Articles/*.md  0.20s user 0.03s system 100% cpu 0.235 total

Unfortunately, my google skills for this haven't come up with a reason why this is happening.

Thanks

Upvotes: 3

Views: 552

Answers (1)

jfriend00
jfriend00

Reputation: 707326

If you're trying to control the order so that mkdirp('build') happens only after rm('build') has completed, then you need to pass a function reference to .then() like this:

rm('build').then(function () {
    return mkdirp('build');
});

Or, you could use .bind():

rm('build').then(mkdirp.bind(null, 'build'));

What you were doing is executing mkdirp() immediately and passing that return value to .then() which doesn't wait to execute it until the promise is resolved.

Upvotes: 3

Related Questions