There could be a million reasons for this. Priority setting wont really come into play here. In the combat example used by Mars666, the dwarf will look for the quickest way back to his bed. If its blocked due monsters, they wont run past with low health and will sleep where they are. Monsters walk up and interrupt them, they fight and ultimately likely die. To counter act this, use the all home command to pull everyone beck. Probably die anyway running past monsters as thats why they didnt do it in the first place. The question here isnt the AI, but why are your dwarfs out alone and vulnerable. Youve already lost in this situation before you ask the AI to save your dwarf.
I think people like to complain the AI is bad a lot more than it really is. No, it is not HAL, but it does the job. To your question why they are standing around with tasks to do... Could be another dwarf assigned far away, could be out of materials, could be something blocking, a door closed, etc... Depends on the task and the situation. Generally speaking when this happens its not a horrible idea to hit the all home command and go right back to normal. Forces dwarf reassignment to all the tasks. You may a get a preferable breakdown of assignment. Or it could assign your best carpenter who was mining a million miles away to make that plank... Its not perfect. In its defense, it cant compensate for your preferences.