promise.then() returns Promise { <pending> }

Viewed 11527

Function fetchData returns a promise and then I'm dealing with that promise in generateURL function by chaining the promise with .then however it returns Promise < pending >. Function generateURL should return a string What am I doing wrong?

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

const fetchData = async () => {
  return await fetch('https://jsonplaceholder.typicode.com/todos/1');
};

const generateURL = () => {
  const baseURL = 'https://cdn.test.com/';
  fetchData().then((res) => {
    const data = res.json();
    console.log('data', data);
    const id = data.id;
    console.log('id', id);
    const generatedURL = `${baseURL}${id}`;
    return generatedURL;
  });
};
 
3 Answers

Reduced your code by a bit instead of adding multiple promise resolution

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

const everything = async () =>{
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    const {id} = await response.json();
    return `https://cdn.test.com/${id}`
}
everything().then((res)=>console.log(res));

having a return await is an anti pattern https://eslint.org/docs/rules/no-return-await

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

const fetchData = () => {
  return fetch('https://jsonplaceholder.typicode.com/todos/1');
};

const generateURL = () => {
  const baseURL = 'https://cdn.test.com/';

  return fetchData().then((res) => {
    const data = res.json();
    console.log('data', data);
    const id = data.id;
    console.log('id', id);
    const generatedURL = `${baseURL}${id}`;

    return generatedURL;
  });
};

generateURL().then(result =>{
console.log(result)

})

You should add another then() for the get result of json() as you can see on document https://www.npmjs.com/package/node-fetch#common-usage

So, it can be like below:

const generateURL = () => {
  const baseURL = 'https://cdn.test.com/';
   fetch('https://jsonplaceholder.typicode.com/todos/1')
   .then(res => res.json())
   .then(data => {
      console.log('data', data);
      const id = data.id;
      console.log('id', id);
      const generatedURL = `${baseURL}${id}`;

      return generatedURL;
  });
};

If you still want to use fetchData function it doesn't need to be async-await, just return fetch because it already returns a Promise.

Related