I'm new to use promise and Q, I'm sure I'm not doing correctly,
please give me some suggestion,
can I use fcall
inside fcall
? because there is a for loop I want to make sure each item image[i]
process a list promise function flow..
I need the response
from beginning to end, input to each promise function then pass to next flow the end return to client side,
but I don't get how to deal with the loop
var response = {};
Q.fcall(function() {
// validate request ...
return response;
})
.then(function(response) {
// save file
for (var i = 0; i < images.length; i++) {
Q.fcall(function() {
// do something with images[i]
return response;
})
.then(function(response) {
// do something with images[i]
return response;
})
.fail(function(error, response) {
response.error = error;
res.send(response);
})
.done(function(response) {
return response;
})
}
return response; << I want this response append data from above loop if above loop all success, then to next flow save db query, if one fail then res.send(), not execute all after
})
.then(function(response) {
// save db query ...
return response
})
.fail(function(error, response) {
response.error = error;
res.send(response);
}).done(function(response) {
res.send(response);
});
Given that images from the response can be processed simultaneously you can use Q.All
to ensure that all images are processed successfully
Q.fcall(verifyRequest)
.then(function(){
return Q.All(images.map(function(image){
return Q.fcall(process1)
.then(process2)
.fail(handleImageError)
}));
})
.then(saveToDB)
.fail(handleRequestError)
Now all you have to do is implement the functions properly making sure data flow is correct.
Make sure that from handleImageError
you return a rejection (return Q.reject();
). Since fail can absorb errors if nothing returned. Actually from your code I think you don't need this handler (process each image failure) because there will be one handler that will respond with error if any of the images fails