繁体   English   中英

如何使用 async/await 语法重写此请求?

[英]How to rewrite this request using async/await syntax?

这是任务:

  1. 您需要使用 fetch 方法对资源发出 GET 请求: https://jsonplaceholder.typicode.com/posts
  2. 将响应保存到 response.json 文件
  3. 只保存那些 id < 20 的项目

我写的:

 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').promisesrequire('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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM