0

I am having trouble understanding how to get a value out of a promise in javascript.

I have these functions:

const getProjectById = (id) => {
  return fetch(`/api/project/${id}`)
    .then((response) => response.json());
}


const getProjectNameFromId = (id) => {
  let name = 'blah';
  getProjectById(id).then((result) => {name = result.name;});
  return name;
}

In the browser's javascript console I have entered these functions and confirmed that when I do something like

let test = getProjectById("52");

it returns a promise, which then resolves to the expected info.

I want to call getProjectNameFromId() to get a project name which I can then pass to a React object as a prop. But instead of getProjectNameFromId() returning the actual project name, it always returns 'blah'.

I understand that the promise is asynchronous and that is why this is not working for me. But I just don't get how to do this properly.

user1002119
  • 3,692
  • 4
  • 27
  • 30

0 Answers0