I have a module that is fetches data from a server and is supposed to return it. But all it does is return {}. I’m not sure why it isn’t waiting. Here’s the basic code:
import {fetch} from ‘wix-fetch’;
export function getData(URL) {
return fetch(URL, {method: “get”})
.then(httpResponse => httpResponse.text())
.then( (text) {
console.log(text);
return text;
})
}
The output has an empty backets, “{}” and then prints the console.log(text) with the actual data I want.
Hi Adam,
Welcome to the Wix Code forums.
It looks like your first .then() function doesn’t have a return, so your second .then() function has nothing to work with.
See the fetch() API for more information including some sample code snippets.
Good luck,
Yisrael
I just tried and it didn’t work. The “console.log(text)” line inside the second .then() function works though.
I don’t have all the details, but you want something like this ( your mileage may vary ):
export function getData(URL) {
return fetch(URL, { method: "get" })
.then((httpResponse) => {
if (httpResponse.ok) {
return httpResponse.text();
}
else {
return Promise.reject("Fetch did not succeed");
}
})
.then((text) => {
console.log(text);
return text;
})
}
I hope this helps,
Yisrael
Thanks Yisrael. My problem was that the function in the page code calling the backend function wasn’t waiting for the backend function to finish before moving on. I had to make the page code use async/await to get it to work properly.