我正在尝试使用Fetch API readable streams下载多个文件。
const files = [.....]; // my file objects
const promises = [];
for (let i = 0; i < files.length; i += 1) {
const file = files[i];
promises.push(
fetch(file.uri)
.then(response => {
const reader = response.body.getReader();
return new ReadableStream({
async start(controller) {
while (true) {
const { done, value } = await reader.read();
// When no more data needs to be consumed, break the reading
if (done) {
break;
}
if (!file.content) {
file.content = value;
}
else {
file.content += value;
}
// Enqueue the next data chunk into our target stream
controller.enqueue(value);
}
// Close the stream
controller.close();
reader.releaseLock();
}
});
})
.then(rs => new Response(rs))
);
}
return Promise.all(promises).then(() => {
// do something else once all the files are downloaded
console.log('All file content downloaded');
});
这里的想法是文件对象只有一个URI。然后此代码将添加内容字段。在此之后我可以做其他事情。
但是,实际上,代码序列不正确。即以下行紧接着彼此运行。
return new ReadableStream({...});
console.log('All file content downloaded');
代码不会等到文件内容下载完毕。上面的日志是提前打印的。运行后我看到代码命中了
while (true) {
循环的代码。即,文件内容是流式传输的。
我显然误解了一个基本概念。我如何等待下载文件内容然后再做其他事情?即流如何使用promise.then()模型。
发现最简单的解决方案是创建自己的承诺。
const files = [.....]; // my file objects
const promises = [];
for (let i = 0; i < files.length; i += 1) {
const file = files[i];
promises.push(
fetch(file.uri)
.then(response => {
return new Promise((resolve, reject) => {
const reader = response.body.getReader();
const stream = new ReadableStream({
async start(controller) {
while (true) {
const { done, value } = await reader.read();
// When no more data needs to be consumed, break the reading
if (done) {
break;
}
if (!file.content) {
file.content = value;
}
else {
file.content += value;
}
// Enqueue the next data chunk into our target stream
controller.enqueue(value);
}
// Close the stream
controller.close();
reader.releaseLock();
}
});
});
})
.then(rs => new Response(rs))
);
}
return Promise.all(promises).then(() => {
// do something else once all the files are downloaded
console.log('All file content downloaded');
});
警告:错误场景也应该优雅地处理。