0

So I have this JS code:

function createServerSideDatasource() {
    return {
        getRows: function(params) {
            console.log('[Datasource] - rows requested by grid: ', params.request);

            let response = getDataFromBackendForDataSource(params.request.startRow, params.request.endRow);
            console.log(response);
        },
    };
}

function getDataFromBackendForDataSource(startRow, endRow) {
    axios.get(
        `./?startRow=${startRow}&endrow=${endRow}`, { 'contentType': 'application/json' }
    ).then((response) => {
        let toSend = response.data
        return toSend
    }).catch((error) => {
        alert(error);
    });
}

The console.log() returns undefined and I don't really understand why.

After some research, I've understood that promises are just syntactic sugar for async/await.

With this information, I expected my code to work as follows:

when the call to getDataFromBackendForDataSource happens
the GET request has launched
createServerSideDatasource waits until the request has finished. (so no console.log yet)
the request has finished. toSend is returned
toSend is assigned to response in createServerSideDatasource
response is logged to the console (not undefined)

but it looks like my thinking is wrong, because I get undefined.

Am I missing something? Why is response undefined?

Thanks.

Octavian Niculescu
  • 1,177
  • 1
  • 3
  • 24
  • `getDataFromBackendForDataSource` has no return statement, so it's implicitly returning undefined. You can return the promise by sticking a return in front of axios.get, as in `return axios.get(/* etc */`. Note that since you'll be returning a promise the code in getRows will need to call `.then` on the promise to interact with the eventual value – Nicholas Tower Jul 26 '22 at 14:11
  • What you are basically are doing is you are ordering a pizza. As soon as you push submit, you try to eat the pizza. You are not waiting for the pizza to be delivered. That is why we have callbacks and async/await. Your getDataFromBackendForDataSource function does not return anything. The return in the then does nothing for the function call. – epascarello Jul 26 '22 at 14:12

0 Answers0