Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
146
rated 0 times [  149] [ 3]  / answers: 1 / hits: 17163  / 10 Years ago, thu, march 27, 2014, 12:00:00

With Q I can define a new promise with:



var queue = q();


But with Bluebird if I do:



var queue = new Promise();


I get:



TypeError: the promise constructor requires a resolver function


How can I get the same result that I had with Q?



This is a snippet of my code:



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 () {
// ...
});

More From » promise

 Answers
8
var resolver = Promise.defer();
setTimeout(function() {
resolver.resolve(something); // Resolve the value
}, 5000);
return resolver.promise;


This line is quite often used in the documentation.



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.



It is, however, discouraged to use this method. Bluebird has even deprecated it.



Instead, you should use this way:



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


See the relevant documentation bits: Promise.defer() and new 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.



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.


[#71753] Wednesday, March 26, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daveon

Total Points: 749
Total Questions: 108
Total Answers: 87

Location: Malaysia
Member since Wed, May 11, 2022
2 Years ago
daveon questions
Sat, Feb 20, 21, 00:00, 3 Years ago
Mon, Nov 23, 20, 00:00, 4 Years ago
Fri, Nov 20, 20, 00:00, 4 Years ago
Fri, Oct 30, 20, 00:00, 4 Years ago
;