使用bluebird和coffeescript的简单promise示例可以工作一半时间 [英] Simple promise example with bluebird and coffeescript works half the time

查看:76
本文介绍了使用bluebird和coffeescript的简单promise示例可以工作一半时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我基本上是在尝试使用Promise写一些简单的代码,而在理解为什么这种特殊代码每隔一段时间就能工作的时候,我有些麻烦。

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.

这是步骤:

┌[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

不幸的是,我对此的Google技能还没有给出发生这种情况的原因。

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

谢谢

推荐答案

如果您要控制顺序,以便 mkdirp('build ')仅在 rm('build')完成之后发生,然后您需要将函数引用传递给。 then()像这样:

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');
});

或者,您可以使用 .bind()

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

您正在执行的是 mkdirp()立即将返回值传递给 .then(),直到承诺被解决,它才等着执行。

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.

这篇关于使用bluebird和coffeescript的简单promise示例可以工作一半时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆