How To Force Resolve A Promise After Certain Duration In Node.js?
I am trying to download a large number images from their url(s) and then creating a PDF file out of them in Node.js. I'm using the image-downloader module to download the images in
Solution 1:
You can use Promise.race()
to add a timeout to each images promise and if you're going to resolve it, then you need to resolve it with some sentinel value (I use null
here in this example) that you can test for so you know to skip it when processing the results.
functiontimeout(t, element) {
returnnewPromise(resolve => {
// resolve this promise with nullsetTimeout(resolve, t, element);
});
}
var promises = data.map(function(element) {
const maxTimeToWait = 6000;
returnPromise.race([download.image(element).then(({ filename }) => {
console.log("Saved to ", filename);
return filename;
}), timeout(maxTimeToWait)]);
});
Then, in your code that processes the results from Promise.all()
, you need to check for null
and skip those because those are the ones that timed out.
Post a Comment for "How To Force Resolve A Promise After Certain Duration In Node.js?"