Traditionally, Banks are in the business of converting interest rate periods.
Suppose you want to lend 1000\$, but get at it whenever you want. If there are 1000 of you, that is 1 million dollars.
Now, you know some people who want to borrow money, but want to be able to keep it for a period of time without having to replay it on demand. Say, they want to spend 1000\$ on an upgraded tool, which will make them an extra 100\$ a year for the next 30 years. They won't have the cash to pay off that tool for a decade or more; so a loan that can be called back "on demand" might bankrupt them.
The bank facilitates this. The bank takes the million\$ of demand deposits, and lends some of it out as a term loan. Most of those people depositing 1000$ in a demand account won't take it out all at the same time; so the bank can "safely" lend that money for longer terms than they guarantee.
They can even do a bunch of 6 month rotating deposits and make it even less likely that the money will be needed before the long term loans finish.
The profit comes from giving the short-term deposits a lower interest rate than the loans you hand out.
This is a kind skimming out of being the middle man.
If things go really badly, that bank can sell the loan it owns for short-term cash to pay off the short-term deposit demand for cash. So long as the loan is healthy and the market is liquid, this can return a profit long before the loan actually matures.
Now, suppose if instead of doing a long term loan, they went off and invested in the stock market. The problem is that the value of stock market assets are less stable than the loan.
So now the bank buys up a bunch of stocks with the 1 million dollars in deposits. The stockmarket drops by 50%, and a bunch of people lose their jobs, and start withdrawing their savings from the bank. Now the bank has to pay off the bank account withdrawals with a distressed asset!
In theory, the mortgages are more stable than the stock market assets. The same economic crash that cause stocks to drop by 50% might drop real estate by 10%, which in turn makes (healthy) mortgages worth 5% less (as they are guaranteed against the principle).
The same call on deposit cash is then easier to answer; sell off some mortgages, and cash is easy to provide. While the asset is slightly distressed, it isn't half value.