I think part of the answer is that you have to have a clear long-term goal that is very important to you, and keeping that goal in mind when are tempted to quit.
If you don't know yourself well enough to know what goal is truly important to you, you risk abandoning your task when the going gets tough. So self-knowledge is also important.
I think that's part of the reason why so many young people don't do that well in school.. they either don't know what they want or think they want one thing when they really don't. Once they mature, understand themselves better and so know what they really want then achieving it could become much easier (assuming they're not burnt out or too old by then).
Also, I'm not by any means a master at this, so I try to look to people who are, and learn from them. For me that means people who've been able to achieve amazing feats of endurance, like Robert Owens[1] and David Goggins[2], or have overcome some incredible adversity, like Brooke Ellison[3] and Kyle Maynard[4].
From some of them, I remember learning to focus on the present, on putting one foot in front of the other, in a kind of hyperfocus on exactly and only the very smallest thing you need to do right now, then doing it again, and again, and again, and again.
Another lesson I'm now remembering learning from many of them is that they built up a stock of achievements they could recall when the going got tough. Knowing that they persevered and succeeded before gave them confidence that they could do it again.
You also have to have hope, be willing to try (and try your best, no matter what the outcome), and somehow overcome depression and other mental issues, if you suffer from them. Therapy works for some, medication or other medical interventions work for others, religion for still others, but ultimately there are no sure or easy answers here.
Having a strong support network and mentors also really helps a lot. It's very difficult to go it alone, though some truly exceptional people manage it (though even then there's usually something in their early life that helped -- often parents or other sources of guidance)... I'm thinking of POW's and concentration camp survivors. Speaking of which, I can highly recommend Victor Frankl's Man's Search for Meaning,[5] as it's about why people endured in the absolute worst circumstances imaginable.
[1] - https://www.youtube.com/watch?v=Yg9kJeule7Q
[2] - https://www.youtube.com/watch?v=78I9dTB9vqM
[3] - https://www.youtube.com/watch?v=alf_I1p7bds
[4] - https://www.youtube.com/watch?v=jqRJ-178dVk
[5] - https://www.amazon.com/Mans-Search-Meaning-Viktor-Frankl/dp/...