0
How can I create traffic lights in Javascript? I have an asynchronous script that runs n times, I wish that when the n tasks had another task been executed. I used normal access to a variable but this can cause race condition. Code Promise:
var load_thumbs_promise = new Promise(function (resolve, reject) {
var itens_id = formData.get('items_id');
itens_id = itens_id.split(",");
itens_id.forEach(function (item, index) {
if(formData.get("type_" + item) == 'pdf')
{
var pdf_url = formData.get("pdf_url_" + item);
PDFJS.getDocument(pdf_url).promise.then(function (doc) {
var page = [];
page.push(1);//Get first page
return Promise.all(page.map(function (num) {
return doc.getPage(num).then(makeThumb)
.then(function (canvas) {
var img = canvas.toDataURL("image/png");
formData.append("pdf_thumb_" + item, img);
console.log(index);
if(index == itens_id.length - 1)
{
console.log("d");
resolve("It's done");
}
});
}));
});
}
});
});
How can I solve this problem?
In question you have "would like when n tasks finish another task to be performed", and that’s what
Promise.all
does, and what are you using. What part does not work?– Sergio
The idea is to perform another task, also asynchronous, when all the tasks performed by load_thumbs_promise ended.
– Andre Alvim
You could use a Promise.all where you make a map instead of
itens_id.forEach
and thenreturn PDFJS.getDocument...
, I think that would be that way. You’ve tested that?– Sergio
I’m not used to using Precedents, I think I don’t quite understand what you suggested but I will search. Thank you.
– Andre Alvim
I will give an answer with a suggestion, as I do not know what this code does risk some bugs, but I think it will help.
– Sergio