Simple promise example with bluebird and coffeescript works half the time

一笑奈何 提交于 2019-12-23 16:08:22

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/31063778/simple-promise-example-with-bluebird-and-coffeescript-works-half-the-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!