When entering US you need two things - approved valid 797 and approved valid visa stamp in passport. If you have B’s approved petition and A’s approved visa stamp you can enter and work for B.
If B’s petition is not approved by the time you return to US, then you need to use A’s petition and have to work for A. There are other complexities w/ this scenario - B’s extension of status will be abandoned as you would have left US and issued I-94 will be for A and not B. So you cannot work for B once their petition gets approved unless you leave US and re-enter on B’s petition.