What is the point of publishing an invention before it is granted? What if it never gets granted?
To the question in the title - 18 months from the filing of the earliest claimed priority filing . . .
Continuing to the question in the body . . . unless you file a non-publication request. In that case, nothing is published unless and until a patent is granted. You can decide that the claims that are allowed are not worth it and stop the process keeping it a trade secret.
This was the US way until the early 2000s. We had no publication of applications until an international treaty (GATT) was signed to harmonize with the rest of the world.
The social contract theory of patents is that society gives limited-time exclusively in return for inventors disclosing their ideas. Europe and Japan had systems where just trying to get exclusivity required dissemination of that knowledge via publication of applications in a big-picture scheme of moving technology forward while the US, prior to GATT, saw the societal trade as more related to the individual.
You can still get that deal. The U.S. negotiated a loophole for applications that would have no foreign counterparts.
To elect non-publication you need to state there is no intention to file out of the country. Then you can keep your invention secret until it issues with the option to abandon the application at the last step if you do not like the claims you get or abandon anywhere along the way if you do not think a good patent will result.