0
import fetch from "node-fetch"
const url = "https://jsonplaceholder.typicode.com/posts/1"
const getData = fetch(url)
getData.then((data)=>{console.log(data.json())})

Making a simple GET request using node-fetch. I am still getting a pending promise here while I am using .then block.

My thesis is that after the promise has resolved that is the data is returned from the server which will send the funciton definition inside the .then block to the microtask queue from where it will be taken to the call stack by the event loop.

  • 3
    `data.json()` returns a promise. See https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch – evolutionxbox Jan 10 '22 at 08:34
  • You can use async/await: ``` const fetch = require('node-fetch'); async function post_request(){ const url = 'https://jsonplaceholder.typicode.com/posts/1'; const res = await fetch(url); const data = await res.json(); console.log(data) } ``` – Souhail HARRATI Jan 10 '22 at 08:44

1 Answers1

1

The process of fetching data is split into two parts.

The first part waits for the meta-information (status code and other headers). The second part for fetching the contents (body) of the response.

import fetch from "node-fetch"
const url = "https://jsonplaceholder.typicode.com/posts/1"
const getData = fetch(url)
getData.then((response)=>{
   // here the meta information of the response is received,
   // but the body might still be transimmited.

   // returns the promise that waits for the body to be received as well
   return data.json()
})
.then((data) => {
  // here the body is received and parsed
  console.log(data)
})

This is especially helpful if the files you request are large or take long to download for other reasons. And you get the information of the files early: like name, size (if the server sends it), ... .

This theoretically (I don't know the exact implementation of fetch-node so I cant say it for sure) should enable the possibility to use it to abort the fetch of the body in case it is too large.

t.niese
  • 39,256
  • 9
  • 74
  • 101