gpt4 book ai didi

javascript - 仅在流结束后才解决 Promise

转载 作者:行者123 更新时间:2023-11-30 19:54:21 24 4
gpt4 key购买 nike

我想知道如何在第一个流结束后才解析并转到下一个数组值,我当前的代码只是对所有 url 执行流,而不是一个一个地执行


const downloadUrl = (url) => {
console.log(url);
console.log("Started :" + url.name);
const writer = fs.createWriteStream(url.name);
return new Promise(resolve => {
return axios({
url: url.url,
responseType: 'stream',
})
.then(response => {
const totalLength = response.headers['content-length'];
const stream = response.data;
let chunksDone = 0;

stream.on('data', (chunk) => {
const chunkLength = chunk.length;
chunksDone += chunkLength;
const percent = ((chunksDone / totalLength) * 100).toFixed(2);
printProgress(url.name, percent)
writer.write(new Buffer(chunk));
})

return streamToPromise(stream);
})
.then(() => {
debugger;
writer.end();
})
.catch(log);
})
}

const streamToPromise = (stream) => {
return new Promise(function (resolve, reject) {
stream.on("end", resolve);
stream.on("error", reject);
})
}

const urls = ['some.mp3','someother.mp3'];
const promise = urls.reduce(function (acc, item) {
return downloadUrl(item)
}, Promise.resolve);

最佳答案

return new Promise(resolve => {
return axios({
url: url.url,
responseType: 'stream',
})

}

这将返回一个永远不会解决的 promise 。删除 new Promise 包装器并 return axios(... directly.

const promise = urls.reduce(function (acc, item) {
return downloadUrl(item)
}, Promise.resolve);

这不会等待任何 promise 。看起来你想要:

const promise = urls.reduce(function (acc, item) {
return acc.then(() => downloadUrl(item));
}, Promise.resolve());

此外,在写入之前,不需要使用 new Buffer 复制 chunk

关于javascript - 仅在流结束后才解决 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54172481/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com