>  기사  >  웹 프론트엔드  >  Javascript Promise에 대한 재미있는 사실

Javascript Promise에 대한 재미있는 사실

Susan Sarandon
Susan Sarandon원래의
2024-10-07 20:21:30146검색

fun facts about Javascript Promises

약속은 항상 비동기적입니다.

Promise의 콜백은 항상 동기 코드 다음에 실행됩니다


const promise = Promise.resolve(); 
promise.then(() => console.log('async')); 
console.log('sync');

//sync
//async



연결된 약속은 새로운 약속을 반환합니다.

Promise는 호출될 때마다 새로운 Promise를 반환합니다


const p = Promise.resolve(); 
const chain = p.then(() => {}); 
console.log(p === chain); //false



그럼 영원히()

무한 체이닝

지원 약속

Promise.resolve(1) 
    .then(value => value + 1) 
    .then(value => value + 1) 
    .then(value => console.log(value)); // 3



콜백을 약속으로 변환할 수 있습니다.

콜백을 사용하는 이전 코드를 최신 async/await와 함께 작동하도록 약속할 수 있습니다


function asyncOperation(callback) { 
    setTimeout(() => callback(null, 'Im a callback'), 1000); 
} 

const promisified = () => new Promise((resolve, reject) => { 
    asyncOperation((err, result) => { 
        if (err) reject(err); 
        else resolve(result); 
    }); 
});

promisified().then(result => console.log(result)); // "Im a callback"



Promise.resolve()가 항상 새로운 Promise를 생성하지는 않습니다.

Promise가 아닌 값을 전달하면 Promise.resolve()는 이를 해결된 Promise로 래핑합니다. 하지만 약속을 전달하면 동일한 약속을 반환합니다.


const p1 = Promise.resolve('Hello'); 
const p2 = Promise.resolve(p1); 
console.log(p1 === p2); // true



체인 어디에서나 오류를 처리할 수 있습니다.


Promise.reject('Error!')
  .then(() => console.log('This will not run'))
  .then(() => console.log('This will also not run'))
  .catch(err => console.log('Caught:', err))
  .then(() => console.log('This will run'));



finally()는 값을 전달하지 않습니다.

finally() 메서드는 확인된 값을 수신하거나 수정하지 않습니다. 리소스를 정리하는 데 사용되며 Promise가 해결되거나 거부되는지 여부에 관계없이 실행됩니다.


Promise.resolve('resolved')
  .then(value => console.log(value))
  .finally(() => console.log('Cleanup'))

//resolved
//cleanup



한번 확정된 약속은 변경할 수 없습니다.

Promise가 확정되면(해결 또는 거부) 해당 상태는 변경할 수 없습니다. 이후에는 다시 해결/거절을 시도해도 변경할 수 없습니다.


const p = new Promise((resolve, reject) => {
  resolve('First');
  resolve('Second');
});
p.then(value => console.log(value));  //"First" (only the first value is used)



특정 오류를 처리하기 위해 catch()를 연결할 수 있습니다.


Promise.reject('type C error')
  .catch(err => {
    if (err === 'type A error') console.log('handle type A');
    throw err;
  })
  .catch(err => {
    if (err === 'type B error') console.log('handle type B');
    throw err;
  })
  .catch(err => {
    if (err === 'type C error') console.log('handle type C');
    throw err;
  })



약속이 아닌 값으로 대기를 사용할 수 있습니다


async function demo() {
  const result = await 42; //not a promise
  console.log(result);      
}
demo(); //42


그렇습니다! 여기까지 읽어주셔서 감사합니다. 다음 시간까지!

위 내용은 Javascript Promise에 대한 재미있는 사실의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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