简体   繁体   中英

How to rewrite this request using async/await syntax?

Here's the task:

  1. You need to make a GET request for the resource: https://jsonplaceholder.typicode.com/posts using fetch method
  2. Save the response to response.json file
  3. Save only those items, where id < 20

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?

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

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. if you don't want to use callback version, you will need to use promise version of appendFile function.

You can import the promise version of fs module as require('fs').promises or 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. You could also wrap the code in this function with try-catch block to handle the errors inside this 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)

 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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