A simple example of a promise with bluebird and coffeescript works in half the time

So, I'm basically trying to write simple code using promises and I'm having trouble understanding why this particular code works every 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 the first run successfully, but the second will fail, etc.

Here are 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 have no reason why this is happening.

thank

+3


source to share


1 answer


If you are trying to control the order so that it mkdirp('build')

only executes after completion rm('build')

, you need to pass a function reference to the .then()

following:

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

      

Or you can use .bind()

:



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

      

What you were doing was to execute immediately mkdirp()

and pass that return value to .then()

, which doesn't wait to be fulfilled until the promise is resolved.

+3


source







All Articles