Very common problem in Retool. This is a good post that describes the pattern I use for that. In fact I use this quite a lot.
You can get more advanced my return values from one javascript query to another:
Another way (using older JS techniques that some are more comfortable with) is to use promises:
https://docs.retool.com/docs/scripting-retool#promises-and-async-queries