How can I create semaphores in JavaScript? I have an asynchronous script that runs n times, I would like it when the n tasks terminate another task to be executed. I used normal access to a variable but this can cause race condition. Promise code:
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 resolve this problem?