[英]How to rewrite this request using async/await syntax?
Here's the task:这是任务:
What I wrote:我写的:
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; } }); });
How to write the same fetch, but with async/await syntax?如何编写相同的 fetch,但使用 async/await 语法?
await
keyword can only be used inside an async
function, so you need to write an async function that makes the API request to fetch the data 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);
}
fs
module of nodeJS has functions that use promises instead of callbacks. nodeJS 的fs
模块具有使用承诺而不是回调的功能。 if you don't want to use callback version, you will need to use promise version of appendFile
function.如果不想使用回调版本,则需要使用 promise 版本的appendFile
function。
You can import the promise version of fs
module as require('fs').promises
or require('fs/promises')
.您可以将fs
模块的 promise 版本导入为require('fs').promises
或require('fs/promises')
。
To handle errors, make sure that code that calls this function has a catch
block to catch and handle any errors that might be thrown from this function.要处理错误,请确保调用此 function 的代码有一个catch
块来捕获和处理此 function 可能引发的任何错误。 You could also wrap the code in this function with try-catch
block to handle the errors inside this function.您还可以使用try-catch
块包装此 function 中的代码,以处理此 function 中的错误。
Side tip: If you want to write data in the file in easily readable format, change小提示:如果您想以易于阅读的格式在文件中写入数据,请更改
const stringified = JSON.stringify(refined);
to至
const stringified = JSON.stringify(refined, null, 4);
Below snippet could help you (tested in node v14)下面的代码片段可以帮助你(在节点 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.