使用浏览器化的bluebird时遇到问题,问题在于promisify功能。
代码:
cat index.js
var Promise = require ('bluebird');
function dosomething (cb) {
cb(null,"I've done something");
}
Promise.promisify(dosomething)()
.then(function(result){
console.log(result);
})
错误:
node bundle.js
/tmp/gulp-test/bundle.js:3880
return makeNodePromisified(callback, receiver, undefined,
^ TypeError: undefined is not a function
at promisify (/tmp/gulp-test/bundle.js:3880:12)
at Function.Promise.promisify (/tmp/gulp-test/bundle.js:3894:15)
at Object.bluebird (/tmp/gulp-test/bundle.js:28:9)
at s (/tmp/gulp-test/bundle.js:1:316)
at e (/tmp/gulp-test/bundle.js:1:487)
at Object.<anonymous> (/tmp/gulp-test/bundle.js:1:505)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
gulpfile:
cat gulpfile.js
var browserify = require('browserify');
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
gulp.task('default', function() {
return browserify('./index.js')
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest('./'));
});
依赖关系:
"dependencies": {
"aws-sdk": "^2.3.4",
"bluebird": "^3.3.5",
"browserify": "^13.0.0",
"gulp": "^3.9.1",
"gulp-uglify": "^1.5.1",
"notp": "^2.0.3",
"thirty-two": "^1.0.1",
"underscore": "^1.8.3",
"vinyl-buffer": "^1.0.0",
"vinyl-source-stream": "^1.1.0"
}
如果我手动创建一个承诺,它可以正常工作:
var Promise = require ('bluebird');
function dosomething (cb) {
cb(null,"I've done something");
}
// manually promisified works fine
function Promisified () {
return new Promise(function(resolve,reject){
dosomething(function(error,result){
if(error){
return reject(error);
}
return resolve(result);
})
})
}
Promisified()
.then(function(result){
console.log(result);
})
我使用的是nodejs 0.12.04,但也是最新的(4.4.3)
有什么想法吗?
答案 0 :(得分:1)
问题是您尝试从为浏览器优化的命令行版本运行。如果你在浏览器中运行它 - 一切都会好的。
但为什么会这样呢?
在此line蓝鸟决定宣传时使用的内容 - makeNodePromisifiedEval
或makeNodePromisifiedClosure
:
var makeNodePromisified = canEvaluate
? makeNodePromisifiedEval
: makeNodePromisifiedClosure;
如果您从命令行运行 - canEvaluate
为真,但由于浏览器版本makeNodePromisifiedEval
的构建时optimization undefined
为{{3}},因为__BROWSER__
将被true
替换。