>  기사  >  웹 프론트엔드  >  Promise에 .then()을 연결할 때 정의되지 않은 값을 피하는 방법은 무엇입니까?

Promise에 .then()을 연결할 때 정의되지 않은 값을 피하는 방법은 무엇입니까?

Linda Hamilton
Linda Hamilton원래의
2024-10-19 22:18:29264검색

How to Avoid Undefined Values When Chaining .then() to Promises?

프라미스에 .then() 연결: 정의되지 않은 값 피하기

여러 .then() 메소드를 프로미스에 연결하는 경우 다음이 중요합니다. 후속 .then() 호출에서 정의되지 않은 값이 발생하지 않도록 각 .then() 핸들러에서 값 또는 Promise를 반환합니다.

예제에서:

<code class="javascript">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
});</code>

여기서 문제는 first .then() 핸들러는 값이나 Promise를 반환하지 않습니다. 결과적으로 두 번째 .then() 핸들러가 호출되면 작업할 내용이 없습니다.

이 문제를 해결하려면 첫 번째 .then() 핸들러의 결과를 반환하면 됩니다.

<code class="javascript">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; // return the result to avoid undefined at next .then()
  });
}

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

이제 두 번째 .then() 핸들러는 첫 번째 핸들러의 결과를 데이터 매개변수로 수신하며 정의되지 않습니다.

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

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