>  기사  >  웹 프론트엔드  >  Promise에 연결된 .then()이 정의되지 않은 값을 반환하는 이유는 무엇입니까?

Promise에 연결된 .then()이 정의되지 않은 값을 반환하는 이유는 무엇입니까?

Susan Sarandon
Susan Sarandon원래의
2024-10-19 22:17:29379검색

Why Does .then() Chained to a Promise Return Undefined?

프로미스에 연결된 .then()이 정의되지 않은 값을 반환하는 이유

아래 코드 조각을 고려하세요.

<code class="js">function doStuff(n) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(n * 10);
    }, Math.floor(Math.random() * 1000));
  })
  .then((result) => {
    if (result > 100) {
      console.log(`${result} is greater than 100`);
    } else {
      console.log(`${result} is not greater than 100`);
    }
  });
}

doStuff(9)
.then((data) => {
  console.log(data); // undefined, why?
});</code>

두 번째 .then() 콜백에서 데이터 값이 정의되지 않은 이유는 무엇입니까?

답변:

Promise에 .then() 콜백을 연결하면 콜백의 반환 값으로 확인되는 새로운 Promise를 반환합니다. 그러나 제공된 코드에서는 첫 번째 .then()에서 값이나 Promise가 반환되지 않습니다.

해결 방법:

문제를 해결하려면 반환해야 합니다. 값을 지정하거나 첫 번째 .then()에서 값이나 Promise를 반환하는 다른 함수를 호출합니다. 코드의 업데이트된 버전은 다음과 같습니다.

<code class="js">function doStuff(n) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(n * 10);
    }, Math.floor(Math.random() * 1000));
  })
  .then((result) => {
    if (result > 100) {
      console.log(`${result} is greater than 100`);
    } else {
      console.log(`${result} is not greater than 100`);
    }

    // Return `result` here to avoid undefined at chained `.then()`.
    return result;
  });
}

doStuff(9)
.then((data) => {
  console.log(`data is: ${data}`); // data is not undefined
});</code>

이 업데이트된 코드에서 첫 번째 .then()은 결과 값(n에 10을 곱함)을 반환합니다. 이는 두 번째 .then()이 수신하도록 보장합니다. 정의된 값을 인수로 사용합니다.

위 내용은 Promise에 연결된 .then()이 정의되지 않은 값을 반환하는 이유는 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.