像 Q 一样定义空的 Bluebird 承诺 [英] Define empty Bluebird promise like in Q

查看:20
本文介绍了像 Q 一样定义空的 Bluebird 承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 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.

但是,不鼓励使用这种方法.Bluebird 甚至弃用了它.

相反,您应该使用这种方式:

Instead, you should use this way:

return new Promise(function(resolve, reject) {
    // Your code
});

查看相关文档位:Promise.defer()new Promise().

See the relevant documentation bits: Promise.defer() and new Promise().

更新您的问题后,您的问题是:您正在重复使用相同的承诺来解决多个值.一个 promise 只能被解析一次.这意味着你必须使用 Promise.defer() 和 promise 一样多的次数.

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.

也就是说,在看到更多代码之后,您似乎真的在使用反模式.使用 Promise 的优势之一是错误处理.对于您的情况,您只需要以下代码:

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 承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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