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?
淡淡烟草味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) {
});