Just three outs away from an important victory, the Yankees suddenly started throwing the ball all over the field — and nearly threw Tuesday night’s game away.

But after Zach Britton made a throwing error on Sam Travis’ comebacker and the Red Sox got to within a run from tying the game, the lefty recovered and got another grounder back to him — this one from Ian Kinsler.

On his second attempt, Britton made a strong throw to Gleyber Torres at second to start a game-ending double play and finish the 3-2 victory.

“Being in that situation before — save situations against that team — I think you lean back on past experiences and slow yourself down,’’ said Britton, the longtime Baltimore closer who was trying to fill the same role for the Yankees on Tuesday. “There’s one pitch you’ve got to make. After I made the error on the throw, you can’t do anything about it. Just make another good pitch.”

And he didn’t have to wait long to redeem himself.

“I don’t think I’ve ever had a do-over right after [an error],’’ Britton said.

Instead of picking up the ball and throwing immediately to second — as he did on the Travis grounder, Britton made sure he had a proper grip on Kinsler’s comebacker, since the ball was “saturated” and difficult to throw.

“It was a little frustrating, but you also know the way Zach was throwing the ball, he was gonna get another opportunity,’’ Aaron Boone said.

The win didn’t just help the Yankees’ cause in the AL wild-card race as they try to hold off the A’s, it also prevented Boston from clinching the AL East title at Yankee Stadium.

“That always serves as motivation,’’ Britton said. “You don’t want anyone celebrating on your home field. We know where we are in the standings. We’ve got to focus on what we can do. It’s tough to think about, but we’re gonna try to keep them from [clinching here].”

For much of the ninth, the Red Sox looked like they might be able to finish the job, with Gary Sanchez letting a third strike get by him to lead off the inning.

The catcher, who allowed a passed ball with J.A. Happ on the mound in the third, barely recovered in time to get Brandon Phillips for the first out.

Britton walked Brock Holt, but got Christian Vazquez to ground to third, where Adeiny Hechavarria had just replaced Miguel Andujar. But Hechavarria made a wide throw to second and Torres couldn’t come up with the ball.

Torres was charged with the error. Torres was covering second when Britton made his first throw to second and Torres appeared to get spiked by pinch-runner Tzu-Wei Lin. Torres stayed in the game and when he got a third chance to turn two, he finally did it.

“That was good poise for a young guy to catch the ball, get the out, turn and make a good throw to [Neil] Walker [at first base],’’ Britton said.