我正在尝试从它们的url下载大量图片,然后在Node.js中创建一个PDF文件。我正在使用图像下载机模块下载承诺链中的图像,然后一旦所有承诺被解析,使用另一个模块图片-to-pdf触发创建pdf。
问题是大部分的承诺在5-6秒内就会被解决,但是有一些图片需要花费相当长的时间才能下载。我想在等待一定时间之后强制触发PDF创建。那能办到吗?
这是代码
var promises = data.map(function(element){
return download.image(element)
.then( ({filename}) => {
console.log("Saved to ",filename);
return filename;
})
});
Promise.all(promises).then(function (data){
var fileName = url.slice(url.indexOf("files")+7, url.length-1).replace("/","_")+".pdf";
data.forEach(
(element) => {console.log(element);
});
imagesToPdf(data, fileName)
.then(console.log(" PDF creation done."));
})
.catch ((error) => {
console.error(error);
});在data.map中传递的数据是一个具有以下性质的JSON对象-
[
{
url:"https://path//to//image//001.jpg",
dest:"local//path//to//image//001.jpg"
},
{
url:"https://path//to//image//002.jpg",
dest:"local//path//to//image//002.jpg"
},
{
url:"https://path//to//image//003.jpg",
dest:"local//path//to//image//003.jpg"
},
...
}]发布于 2020-12-27 06:26:44
您可以使用Promise.race()为每个图像添加一个超时承诺,如果要解决这个问题,则需要使用一些哨位值(在本例中使用null )解析它,以便您知道在处理结果时跳过它。
function timeout(t, element) {
return new Promise(resolve => {
// resolve this promise with null
setTimeout(resolve, t, element);
});
}
var promises = data.map(function(element) {
const maxTimeToWait = 6000;
return Promise.race([download.image(element).then(({ filename }) => {
console.log("Saved to ", filename);
return filename;
}), timeout(maxTimeToWait)]);
});然后,在处理来自Promise.all()的结果的代码中,您需要检查null并跳过这些结果,因为这些结果是超时的。
https://stackoverflow.com/questions/65463307
复制相似问题