像Q中那样定义空的Bluebird Promise [英] Define empty Bluebird promise like in Q
问题描述
使用Q,我可以使用以下方法定义新的承诺:
With Q I can define a new promise with:
var queue = q();
但如果我愿意,可以和Bluebird一起
But with Bluebird if I do:
var queue = new Promise();
我得到:
TypeError: the promise constructor requires a resolver function
如何获得与Q相同的结果?
How can I get the same result that I had with Q?
这是我的代码的片段:
var queue = q()
promises = [];
queue = queue.then(function () {
return Main.gitControl.gitAdd(fileObj.filename, updateIndex);
});
// Here more promises are added to queue in the same way used above...
promises.push(queue);
return Promise.all(promises).then(function () {
// ...
});
推荐答案
var resolver = Promise.defer();
setTimeout(function() {
resolver.resolve(something); // Resolve the value
}, 5000);
return resolver.promise;
文档中经常使用此行.
请注意,这通常是使用它的反模式.但是,如果您知道自己在做什么,那么Promise.defer()
是一种获取与Q相似的解析器的方法.
Be aware that this is usually an anti-pattern to use that. But if you know what you're doing, Promise.defer()
is a way to get the resolver that is similar Q's way.
但是,不建议使用此方法.蓝鸟甚至已弃用它.
相反,您应该使用这种方式:
Instead, you should use this way:
return new Promise(function(resolve, reject) {
// Your code
});
请参阅相关文档: Promise.defer()和新Promise().
问题更新后,这就是您的问题:您正在重复使用相同的诺言来解决多个值. 一个承诺只能被解决一次.这意味着您必须多次使用Promise.defer()
来实现承诺.
After the update of your question, here is your issue: you're reusing the same promise to resolve several values. A promise can only be resolved once. It means you have to use Promise.defer()
as many times as you have promises.
也就是说,看完更多代码后,看来您真的在使用反模式.使用诺言的一个优势是错误处理.对于您的情况,您只需要以下代码:
That said, after seeing more of your code, it seems you're really using anti-patterns. One advantage of using promises is error handling. For your case, you'd just need the following code:
var gitControl = Promise.promisifyAll(Main.gitControl);
var promises = [];
promises.push(gitControl.gitAddAsync(fileObj.filename, updateIndex));
return promises;
这应该足以处理您的用例.它更清晰,并且还具有确实正确地处理错误的优点.
This should be enough to handle your use case. It is a lot clearer, and it also has the advantage of really handling the errors correctly.
这篇关于像Q中那样定义空的Bluebird Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!