[英]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.