我想答案已经在这个问题上了
.then()
似乎是
.pipe()
你在寻找。
可能缺少的是
(result)
(results)
{name, content}
产生于
Promise.mapSeries(urls, ...)
.
Promise.mapSeries(urls, url => {
return request.getAsync({'url':url, 'encoding':'binary'}).spread((response, body) => {
if (response.statusCode == 200) {
return {
'name': url.match(/\/([^/]*)$/)[1], // get the last part of url (file name)
'content': body
};
} else if (response.statusCode == 404) {
throw new Error(`The archive ${url.match(/\/([^/]*)$/)[1]} does not exist`);
} else {
throw new Error(`Unsuccessful attempt. Code: ${response.statusCode}`);
}
});
}).then((results) => {
// Here write each `result.content` to file.
}).catch((error) => {
console.error(error);
});
实际上,你可能不会选择这样写,因为
getAsync()
需要在任何写入开始之前完成。
在大多数情况下(也可能是您想要的情况下),更好的流应该是来自每个成功用户的内容
getAsync()
尽快写好:
Promise.mapSeries(urls, url => {
let name = url.match(/\/([^/]*)$/)[1]; // get the last part of url (file name)
return request.getAsync({'url':url, 'encoding':'binary'}).spread((response, body) => {
if (response.statusCode == 200) {
// write `body.content` to file.
} else if (response.statusCode == 404) {
throw new Error(`The archive ${name} does not exist`);
} else {
throw new Error(`Unsuccessful attempt. Code: ${response.statusCode}`);
}
});
}).catch((error) => {
console.error(error);
});
-
捕获单个url/获取/写入错误
-
编译成功/失败统计。
Promise.mapSeries(urls, url => {
let name = url.match(/\/([^/]*)$/)[1] || ''; // get the last part of url (file name)
if(!name) {
throw new RangeError(`Error in input data for ${url}`);
}
return request.getAsync({'url':url, 'encoding':'binary'}).spread((response, body) => {
if (response.statusCode == 200) {
// write `body.content` to file.
return { name, 'content': body };
} else if (response.statusCode == 404) {
throw new Error(`The archive ${name} does not exist`);
} else {
throw new Error(`Unsuccessful attempt. Code: ${response.statusCode}`);
}
})
.catch(error => ({ name, error }));
}).then((results) => {
let successes = results.filter(res => !res.error).length;
let failures = results.filter(res => !!res.error).length;
let total = results.length;
console.log({ successes, failures, total }); // log success/failure stats
}).catch((error) => {
console.error(error); // just in case some otherwise uncaught error slips through
});