簡體   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