[英]How to rewrite this request using async/await syntax?
这是任务:
我写的:
const fetch = require('node-fetch'); const fs = require('fs'); const path = require('path'); const filePath = path.join(__dirname, 'response.json'); fetch('https://jsonplaceholder.typicode.com/posts').then(res => res.json()).then(data => { const refined = data.filter(item => item.id < 20); const stringified = JSON.stringify(refined); fs.appendFile(filePath, stringified, err => { if (err) { throw err; } }); });
如何编写相同的 fetch,但使用 async/await 语法?
await
关键字只能在async
function 中使用,因此您需要编写一个异步 function 来发出 API 请求来获取数据
async function fetchData() {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await response.json();
const refined = data.filter(item => item.id < 20);
const stringified = JSON.stringify(refined);
// promise version of appendFile function from fs.promises API
await fs.appendFile(filePath, stringified);
}
nodeJS 的fs
模块具有使用承诺而不是回调的功能。 如果不想使用回调版本,则需要使用 promise 版本的appendFile
function。
您可以将fs
模块的 promise 版本导入为require('fs').promises
或require('fs/promises')
。
要处理错误,请确保调用此 function 的代码有一个catch
块来捕获和处理此 function 可能引发的任何错误。 您还可以使用try-catch
块包装此 function 中的代码,以处理此 function 中的错误。
小提示:如果您想以易于阅读的格式在文件中写入数据,请更改
const stringified = JSON.stringify(refined);
至
const stringified = JSON.stringify(refined, null, 4);
下面的代码片段可以帮助你(在节点 v14 中测试)
const fetch = require("node-fetch") const fs = require("fs") const path = require("path") const filePath = path.join(__dirname, "response.json") async function execute() { const res = await fetch("https://jsonplaceholder.typicode.com/posts") const data = await res.json() const refined = data.filter((item) => item.id < 20) const stringified = JSON.stringify(refined) fs.appendFile(filePath, stringified, (err) => { if (err) { throw err } }) } execute()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.