Reputation: 731
I need to get some data from a grpc response and return that data. How can I wait for the data to be ready in order to run the rest of my code and return the data?
I tried placing a while loop to wait for the response of the function but it just gets stuck there forever. I need to either update some global variables or try to capture the response from the requestQueryTreeItemCommand function.
I know I probably must use some kind of callback or Promise, but I just don't know how to hook it up to this code.
function queryTreeItem(elem) {
var requestQueryTreeItemCommand = new messages.QueryTreeItemRequest();
requestQueryTreeItemCommand.setItem(elem.textContent);
function queriedItemCallbackFunc(err, response) {
if (err) {
console.log(err);
responded = true;
response_str = "";
return response_str;
} else {
responded = true;
response_str = response.getMessage();
return response_str;
}
}
client.queryTreeItem(requestQueryTreeItemCommand, queriedItemCallbackFunc); // Requests stuff and calls queriedItemCallbackFunc when the other side responds back.
// while (!responded) {
// console.log("JS-DEBUG");
// console.log(responded);
// console.log(response_str);
// }
// While loop doesn't work, keeps looping forever.
// Somehow wait for queriedItemCallbackFunc to update the global variable 'response_str',
// or somehow capture the return of queriedItemCallbackFunc and don't use global variables.
responded = false;
return response_str;
}
Upvotes: 2
Views: 2987
Reputation: 20297
Fundamentally, it is impossible to do exactly what you are asking for here. A gRPC request is an asynchronous operation, and returning from a function is a synchronous operation. You cannot wait for an asynchronous operation to complete before returning from a function.
You can approximate the code appearance of synchronous code using async/await
, but that would just push the problem one layer up. Doing that would make queryTreeItem
asynchronous, and then whatever function calls it would have the same problem you have now.
The only real solution here is to code more broadly in an asynchronous style, using callbacks and/or promises and/or async/await
instead of return values to handle the results of asynchronous actions.
Upvotes: 2