0

I have a server-side function that outputs a value from a database to /.netlify/functions/todos-read
I need to read it on another page, however the read() function returns undefined instead.

Here is what i tried:

function read() {
   fetch('/.netlify/functions/todos-read').then(res => res.json()).then((out) => {
      return out
   }).catch(err => console.error(err));
}

Here is what i expected it to return:

{"ref":{"@ref":{"id":"236323245287014920","class":{"@ref":{"id":"nappi","class":{"@ref":{"id":"classes"}}}}}},"ts":1561634259400000,"data":{"value":1}}
Skelly
  • 109
  • 1
  • 10
  • When you `return` you're returning to the inner callback function (placed in `.then()`), not to the outer `read()` function. See the above link on how to return from an async call – Nick Parsons Jul 04 '19 at 16:12

1 Answers1

1

Your read() function should return a promise, and callers should expect one...

function read() {
   return fetch('/.netlify/functions/todos-read').then(res => res.json());
}

// call it
read().then(res => {
    console.log(res);
}).catch(error => {
    console.log(error);
});
danh
  • 62,181
  • 10
  • 95
  • 136
  • this helped, if i wanted to set a text to display the contents of an json object using this code how would i go about it? so far ive gotten [object Object] to be displayed :DD edit: i got it to work – Skelly Jul 04 '19 at 17:16
  • Set text to one of the string properties in the json or to ‘JSON.stringify(res)’ – danh Jul 04 '19 at 20:50