Request-promise Unhandled Rejection Requesterror: Error: Etimedout
Hi i try to write some download function by promise request, but if i have a timeout i cant handled this error , i try meny example but still have this error Unhandled rejection Re
Solution 1:
I have a solution , if you use a request-promise you shout create promise and return him and catch the exeption , it dont work with pipe like in my case so we need change the function download like
functiondownloadPhoto(url){
var options = {
uri:url,
timeout:10000,
encoding: 'binary'
};
returnrp(options);
}
and then we can use it like
returndownloadPhoto(url).then(function(file){
fs.writeFileSync(name+'.jpg', file, 'binary');
}).catch(function(err){
console.log(err);
});
and we can use map
Promise.map(photos, function(photo) {
if(photo.type === 'photo'){
return sndPht(photo,uploadUrl);
}
},{concurrency: 1});
but if you need downlod large file you need use request with calback's
Solution 2:
You can use Promise.race
to use the value from the first promise that resolves or rejects.
Using this technique we can have an error that will timeout after a period of time if the download is taking too long. The downloadPhoto
Promise will still resolve, but it will not be handled
const images = [
{ url: 'www.foo.com', uploadUrl: '/foo', name: 'foo' }
, { url: 'www.bar.com', uploadUrl: '/bar', name: 'bar' }
, { url: 'www.baz.com', uploadUrl: '/baz', name: 'baz' }
]
constpromiseTimeout = (delay, promise) =>
Promise.race([
newPromise((resolve, reject) =>setTimeout(resolve, delay, {
status: 'error',
msg: 'took too long!'
})
),
promise
])
constdownloadPhoto = ({ url, uploadUrl, name }) =>
promiseTimeout(
1000,
newPromise((resolve, reject) => {
setTimeout(resolve, 3000, {
status: 'success',
msg: `this will never resolve ${url}`
})
})
)
// map images array [...image] into [...Promise(image)]const imagePromises = images.map(downloadPhoto)
// resolve all promisesPromise.all(imagePromises)
// called once all promises are resolved with array of results
.then(images => {
// map over the resolved images and do further processing
images.map(console.log.bind(console, 'Image resolved'))
})
// promises no longer reject, you will need to look at the status
.catch(console.log.bind(console, 'Error: '))
Post a Comment for "Request-promise Unhandled Rejection Requesterror: Error: Etimedout"