JavaScript
Promise 예제
포시
2022. 6. 18. 16:41
728x90
예제1
var products = [{
name1: 'chair', // name, price로 되야하는 상황
price1: 7000,
}, ];
function change() { // products의 key에서 숫자 오타를 없애는 함수
for (obj of products) {
for (a in obj) {
if (!isNaN(a.slice(-1))) {
var newA = a.slice(0, a.length - 1);
obj[newA] = obj[a];
delete obj[a];
}
}
}
}
var 프로미스 = new Promise(function (resolve, reject) {
console.log(products);
resolve();
})
프로미스.then(function () {
// 프로미스 내부 console.log() 실행 후 resolve()를 통해 then()의 콜백 함수 실행
change();
console.log(products);
})
결과
[ { name1: 'chair', price1: 7000 } ]
[ { name: 'chair', price: 7000 } ]
예제2
const firstPromise = Promise.resolve('First');
firstPromise.then(console.log);
// 이런 특성을 이용해 응용하면 아래와 같이 사용할 수 있다.
const countPromise = Promise.resolve(0);
function increment(value) {
return value + 1;
}
const resultPromise = countPromise.then(increment).then(increment).then(increment);
resultPromise.then(console.log);
결과
First
3
728x90