search

Home  >  Q&A  >  body text

node.js - request's pipe method, how to monitor the time required to read a file?

To read a picture from the Internet, I need to know the time required. For example, if it exceeds 3 seconds, I will give up reading the picture. How to do this?

怪我咯怪我咯2741 days ago723

reply all(1)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-05-24 11:40:32

    You can use promises

    const p = Promise.race([
      request('/resource-that-may-take-a-while'),//下载图片 改成真正的下载
      new Promise(function (resolve, reject) {
        setTimeout(() => reject(new Error('request timeout')), 3000)
      })
    ]);
    p.then(response => console.log(response));
    p.catch(error => console.log(error));

    Or use async package

    async.race([
        function(callback) {
            request('/resource-that-may-take-a-while',callback)//下载图片 改成真正的下载
        },
        function(callback) {
            setTimeout(function() {
                callback(null, 'two');
            }, 3000);
        }
    ],
    // main callback
    function(err, result) {
        
    });

    reply
    0
  • Cancelreply