-1

I'm fairly new to node fetch and I'm doing a simple get request to get a list of my postman collections. I'm able to get the response text and console log it in the function but when I'm returning the responseText to a variable and logging it, I get an empty result,could someone suggest why?

const fetch = require("node-fetch");
async function getCollections() {
  var myHeaders = new fetch.Headers();
  myHeaders.append(
    "X-Api-Key",
    "<API-KEY>"
  );
  var requestOptions = {
    method: "GET",
    headers: myHeaders,
  };
  url = "https://api.getpostman.com/collections";
  const requestResponse = await fetch(url, requestOptions);
  const response = await requestResponse.text();
  return response;
}

const result = getCollections();
console.log(result);
  • 2
    You're not awaitng getCollections() in your result varaible. Should be: const reuslt = await getCollections(); That should fix your issue. – Kwright02 Jun 07 '21 at 03:31

1 Answers1

0

It looks like you are logging result before the async function has a chance to return the resolved promise. I can think of two ways to resolve this:

const fetch = require("node-fetch");

async function getCollections() {
  var myHeaders = new fetch.Headers();
  myHeaders.append(
    "X-Api-Key",
    "<API-KEY>"
  );
  var requestOptions = {
    method: "GET",
    headers: myHeaders,
  };
  url = "https://api.getpostman.com/collections";
  const requestResponse = await fetch(url, requestOptions);
  const response = await requestResponse.text();
  return response;
}

getCollections().then(console.log);

Or moving the console log inside the asynchronous function.

const fetch = require("node-fetch");
async function getCollections() {
  var myHeaders = new fetch.Headers();
  myHeaders.append(
    "X-Api-Key",
    "<API-KEY>"
  );
  var requestOptions = {
    method: "GET",
    headers: myHeaders,
  };
  url = "https://api.getpostman.com/collections";
  const requestResponse = await fetch(url, requestOptions);
  const response = await requestResponse.text();
  console.log(response)
  return response;
}

getCollections()
Ross Moody
  • 773
  • 3
  • 16