[英]JavaScript NodeJS How to use stream/promises with async functions?
我在 Node 中有一个 JS 异步 function。 比如说,它从 URL 下载一个文件并用它做一些事情,例如。 解压它。 我是这样写的,它可以工作,但是eslint
告诉我有一股浓浓的代码味道: error Promise executor functions should not be async no-async-promise-executor
。 由于正文 function 中的await fetch
,因此需要Async
。
我对流不够熟练,也没有async/await
streams
自己纠正它。 我想摆脱 Promise 并完全使用async/await
。 模块stream/promises
似乎是从 Node-15 到 go 的方式,如此处how-to-use-es8-async-await-with-streams所评论。 如何在这种情况下使用await pipeline(...)
? 也许有更好更短的方法?
这是 function:
function doSomething(url) {
return new Promise(async (resolve, reject) => {
try {
const fileWriteStream = fs.createWriteStream(someFile, {
autoClose: true,
flags: 'w',
});
const res = await fetch(url);
const body = res.body;
body
.pipe(fileWriteStream)
.on('error', (err) => {
reject(err);
})
.on('finish', async () => {
await doWhatever();
resolve('DONE');
});
} catch (err) {
reject(err);
}
});
}
您可以在到达执行程序之前简单地执行await
:
async function doSomething(url) {
const fileWriteStream = fs.createWriteStream(someFile, { autoClose: true, flags: 'w' });
let { body } = await fetch(url);
body.pipe(fileWriteStream);
return new Promise((resolve, reject) => {
body.on('error', reject);
body.on('finish', resolve);
});
};
我的一般建议是尽可能多地从 promise 执行程序中删除代码。 在这种情况下,Promise 只需要捕获分辨率/拒绝。
请注意,我还从doSomething
中删除doWhatever
- 这使得doSomething
更加健壮。 你可以简单地做:
doSomething('http://example.com').then(doWhatever);
最后,我建议您将someFile
设置为doSomething
的参数,而不是从更广泛的上下文中引用它!
要使用您正在寻找的pipeline
function,它将是
const { pipeline } = require('stream/promises');
async function doSomething(url) {
const fileWriteStream = fs.createWriteStream(someFile, {
autoClose: true,
flags: 'w',
});
const res = await fetch(url);
await pipeline(res.body, fileWriteStream);
await doWhatever();
return 'DONE';
}
您可以在 NodeJS 中使用fs/promises
并将您的代码缩减为以下内容:
import { writeFile } from 'fs/promises'
async function doSomething(url) {
const res = await fetch(url);
if (!res.ok) throw new Error('Response not ok');
await writeFile(someFile, res.body, { encoding: 'utf-8'})
await doWhatever();
return 'DONE';
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.