const timeout = new Promise((resolve, reject) => { const id = setTimeout(() => { clearTimeout(id); reject('timeout!'); }, 500); });
const promise = new Promise((resolve, reject) => { const id = setTimeout(() => { clearTimeout(id); resolve('response!'); }, 700); });
Promise.race([promise, timeout]).then(response => { console.log(response); }).catch(err => { console.log(err) //timeout! });
promise
const onClickPromise = async () => { console.time("Promise 요청"); const result1 = await new Promise((resolve, reject) => { setTimeout(() => { resolve("https://dog1.jpg"); }, 3000); }); console.log(result1); const result2 = await new Promise((resolve, reject) => { setTimeout(() => { resolve("https://dog2.jpg"); }, 1000); }); console.log(result2); const result3 = await new Promise((resolve, reject) => { setTimeout(() => { resolve("https://dog3.jpg"); }, 2000); }); console.log(result3); console.timeEnd("Promise 요청"); // 6초 };
promise.all
const onClickPromiseAll = async () => { console.time("PromiseAll 요청"); const result = await Promise.all([ new Promise((resolve, reject) => { setTimeout(() => { resolve("https://dog1.jpg"); }, 3000); }), new Promise((resolve, reject) => { setTimeout(() => { resolve("https://dog2.jpg"); }, 1000); }), new Promise((resolve, reject) => { setTimeout(() => { resolve("https://dog3.jpg"); }, 2000); }), ]); console.timeEnd("PromiseAll 요청"); // 3초 }
*결론
간단한 요청시에는 Promise로 처리해도 상관은 없지만 많은 요청이 필요할 때에는 Promise.all로 요청하는게 더 효율적이다.