request-promise Unhandled rejection RequestError: Error: ETIMEDOUT

request-promise Unhandled rejection RequestError: Error: ETIMEDOUT

嗨,我尝试通过 promise 请求编写一些下载功能,但是如果我有超时我无法处理这个错误,我尝试了很多例子但仍然有这个错误

Unhandled rejection RequestError: Error: ETIMEDOUT
    at new RequestError (/home/parse/node_modules/request-promise-core/lib/errors.js:14:15)
    at Request.plumbing.callback (/home/parse/node_modules/request-promise-core/lib/plumbing.js:87:29)
    at Request.RP$callback [as _callback] (/home/parse/node_modules/request-promise-core/lib/plumbing.js:46:31)
    at self.callback (/home/parse/node_modules/request/request.js:186:22)
    at emitOne (events.js:101:20)
    at Request.emit (events.js:191:7)
    at Timeout._onTimeout (/home/parse/node_modules/request/request.js:816:16)
    at ontimeout (timers.js:380:14)
    at tryOnTimeout (timers.js:244:5)
    at Timer.listOnTimeout (timers.js:214:5)

我的代码

下载功能:

function downloadPhoto(url,uploadUrl,name){
   return new Promise(function(resolve, reject){
        rp(url,{timeout:15000},function(e){if(e) reject(e);}).on('error', function(e){return reject(e);}).pipe(fs.createWriteStream(name+'.jpg')).on('finish', () => {
        //console.log('done Download photo');
         return resolve();
    });
  });

}

调用这个函数

function sndPht(url,uploadUrl){
    return new Promise(function(resolve, reject){
      return downloadPhoto(url,uploadUrl,name).then(function(){
             ..... some logic .....  
        }).catch(function(err){
            return reject(err);
        });
}

对于许多文件,我在 bluebird js 映射中调用函数:

Promise.map(photos, function(photo) {
  if(photo.type === 'photo'){
    return sndPht(photo,uploadUrl);
  }  
},{concurrency: 1});

我做错了什么?

您可以使用 Promise.race 来使用第一个解决或拒绝的承诺的值。

使用此技术,如果下载时间过长,我们可能会遇到一段时间后超时的错误。 downloadPhoto Promise 仍将解析,但不会被处理

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' }
]

const promiseTimeout = (delay, promise) => 
  Promise.race([
    new Promise((resolve, reject) => 
      setTimeout(resolve, delay, {
        status: 'error',
        msg: 'took too long!'
      })
    ),
    promise
  ])

const downloadPhoto = ({ url, uploadUrl, name }) => 
  promiseTimeout(
    1000,
    new Promise((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 promises
Promise.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: '))

我有一个解决方案,如果你使用请求承诺,你会喊出创建承诺并 return 他并捕获异常,它不能像我的情况那样使用管道,所以我们需要像这样更改函数下载

function downloadPhoto(url){
  var options = {
      uri:url,
      timeout:10000,
      encoding: 'binary'
  };

  return rp(options);
}

然后我们可以像

一样使用它
return downloadPhoto(url).then(function(file){
      fs.writeFileSync(name+'.jpg', file, 'binary');
    }).catch(function(err){
     console.log(err);
});

我们可以使用地图

Promise.map(photos, function(photo) {
  if(photo.type === 'photo'){
    return sndPht(photo,uploadUrl);
  }  
},{concurrency: 1});

但是如果您需要下载大文件,您需要使用 request with calback's