【发布时间】:2015-08-02 04:56:31
【问题描述】:
我一直在尝试养成使用 Promise 的习惯,但在 Meteor 上下文中尝试在服务器端代码中使用 Promise 时遇到了问题。这就是问题所在:
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
p = function(){
return new Promise(function(res,rej) {
res("asd");
});
};
p().then(function(asd){
console.log("asd is " + asd);
return "zxc"
}).then(Meteor.bindEnvironment(function(zxc){
console.log("zxc is " + zxc);
return "qwe"
})).then(function(qwe){
console.log("qwe is " + qwe);
});
});
}
mvrx:bluebird 包已安装
代码也可以在GitHub获得
预期输出:
asd is asd
zxc is zxc
qwe is qwe
实际输出:
asd is asd
zxc is zxc
qwe is undefined
删除 Meteor.bindEnvironment 包装器可以解决问题,但我需要它才能在回调中使用集合
那么我在这里缺少什么?是不能以这种方式使用 Promises + Meteor 还是有错误?
我实际上想要完成的是具有重要部分结果但需要同步结束的并行管道。像这样。
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
promises = [];
step1 = function(input){
return new Promise(function(res, rej){
console.log(input + ":Step 1");
res(input);
});
};
step2 = function(input){
return new Promise(function(res, rej){
console.log(input + ":Step 2");
res(input);
});
};
step3 = function(input){
return new Promise(function(res, rej){
console.log(input + ":Step 3");
res(input);
});
};
slowIO = function(input){
var inp = input;
return new Promise( function(res,rej){
setTimeout(function(){
console.log(inp + ":SlowIO");
res(inp);
},Math.random()*20000);
});
};
end = function(input){
return new Promise(function(res,rej){
console.log(input + ": done, commiting to database");
res()
});
};
for (var i = 0; i < 100; ++i) {
promises.push(step1("pipeline-" + i).then(step2).then(slowIO).then(step3).then(end));
};
Promise.all(promises).then(function(){
console.log("All complete")
});
});
}
【问题讨论】:
-
您可以使用
Promise.promisify承诺bindEnvironment,因为它是错误的,请查看文档
标签: javascript meteor promise bluebird