"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > JavaScript Promise .then() 핸들러는 언제 서로 관련하여 실행됩니까?

JavaScript Promise .then() 핸들러는 언제 서로 관련하여 실행됩니까?

2024년 12월 11일에 게시됨
검색:145

When do JavaScript Promise .then() Handlers Execute in Relation to Each Other?

JavaScript Promise의 실행 순서 이해

JavaScript의 Promise는 특정 이벤트 또는 Promise가 발생하면 코드가 실행되는 비동기 프로그래밍 모델을 제공합니다. ,이(가) 충족됩니다. 그러나 여러 Promise를 처리할 때는 예측할 수 없는 동작을 피하기 위해 실행 순서를 이해하는 것이 중요합니다.

다음 코드 조각을 고려하세요.

Promise.resolve('A')
  .then(function(a){console.log(2, a); return 'B';})
  .then(function(a){
     Promise.resolve('C')
       .then(function(a){console.log(7, a);})
       .then(function(a){console.log(8, a);});
     console.log(3, a);
     return a;})
  .then(function(a){
     Promise.resolve('D')
       .then(function(a){console.log(9, a);})
       .then(function(a){console.log(10, a);});
     console.log(4, a);})
  .then(function(a){
     console.log(5, a);});
console.log(1);
setTimeout(function(){console.log(6)},0);

실행 시 다음과 같은 출력 순서를 볼 수 있습니다.

1
2 "A"
3 "B"
7 "C"
4 "B"
8 undefined
9 "D"
5 undefined
10 undefined
6

실행 순서 이해

  1. 프로미스는 비동기적으로 해결됩니다.
    프로미스는 현재 실행 스레드와 독립적으로 해결됩니다. 이는 .then() 핸들러가 현재 스레드가 완료된 후 비동기적으로 호출된다는 것을 의미합니다.
  2. 큐에서 약속 실행:
    .then() 핸들러는 이전 스레드 이후에 실행되도록 예약됩니다. 핸들러가 완료됩니다. 본질적으로 대기열에 있으므로 1, 2 "A", 3 "B"가 순서대로 인쇄되는 것을 볼 수 있습니다.
  3. 내부 약속 독립 체인 생성:
    Promises 생성 Promise.resolve('C') 및 Promise.resolve('D')와 같은 중첩된 .then() 핸들러 내에서 새롭고 독립적인 Promise를 생성합니다. 체인. 이러한 내부 체인은 본질적으로 외부 체인과 동기화되지 않습니다.
  4. 실행 순서는 결정적이지 않습니다:
    이러한 독립 체인의 실행 순서는 보장되지 않습니다. 이 경우 Promise 엔진은 6행과 7행의 핸들러보다 먼저 5행과 12행의 .then() 핸들러를 실행하도록 선택합니다.

권장사항

특정 실행 순서를 보장하려면 동기화되지 않은 약속 체인을 만드는 것을 피하고 대신 순차적인 방식으로 연결하는 약속에 의존하세요. 아래와 같이 내부 .then() 핸들러에서 Promise를 반환하여 상위 Promise와 연결합니다.

Promise.resolve('A').then(function (a) {
    console.log(2, a);
    return 'B';
}).then(function (a) {
    var p = Promise.resolve('C').then(function (a) {
        console.log(7, a);
    }).then(function (a) {
        console.log(8, a);
    });
    console.log(3, a);
    return p; // Link the inner promise to the parent chain
}).then(function (a) {
    var p = Promise.resolve('D').then(function (a) {
        console.log(9, a);
    }).then(function (a) {
        console.log(10, a);
    });
    console.log(4, a);
    return p; // Link the inner promise to the parent chain
}).then(function (a) {
    console.log(5, a);
});

console.log(1);

setTimeout(function () {
    console.log(6)
}, 0);

이 접근 방식을 사용하면 실행 순서가 완전히 결정적이 됩니다. 1, 2 "A", 3 "B", 7 "C", 8 정의되지 않음, 4 정의되지 않음, 9 "D", 10개는 정의되지 않음, 5개는 정의되지 않음, 6개.

릴리스 선언문 이 글은 1729739979에서 재인쇄되었습니다. 침해 내용이 있는 경우, [email protected]으로 연락하여 삭제하시기 바랍니다.
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3