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

Susan Sarandon
풀어 주다: 2024-10-25 08:19:28
원래의
394명이 탐색했습니다.

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

권장 사항

특정 실행 순서를 보장하려면 동기화되지 않은 Promise 체인 생성을 피하고 대신 Promise를 순차적으로 연결하는 데 의존하세요. 아래와 같이 내부 .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.

위 내용은 JavaScript Promise .then() 핸들러는 언제 서로 관련하여 실행됩니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!