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
실행 순서 이해
권장사항
특정 실행 순서를 보장하려면 동기화되지 않은 약속 체인을 만드는 것을 피하고 대신 순차적인 방식으로 연결하는 약속에 의존하세요. 아래와 같이 내부 .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개.
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3