728x90
콜백 함수는 다른 코드에 인자로 넘겨줌으로써 그 제어권도 함께 위임하는 함수
map 메서드
Array.prototype.map(callback[,thisArg])
callback: function(currentValue, index, array)
첫번째로 인자로 callback 함수를 받고, 생략 가능한 두 번째 인자로 콜백함수 내부에서 this로 인식할 대상을 특정할 수 있습니다.
Array.prototype.map = function(callback, thisArg){
var mappedArr = []
for(let i = 0; i < this.length; i++){
let mappedValue = callback.call(thisArg || window, this[i], i this)
mappedArr[i] = mappedValue
}
return mappedArr
}
콜백함수 내부의 this에 다른 값 바인딩하기
const obj1 = {
name: 'obj1',
func:function(){
console.log(this.name)
}
}
setTimeout(obj1.func.bind(obj1),1000)
const obj2 = {name: 'obj2'}
setTimeout(obj1.func.bind(obj1),1500)
콜백 지옥
콜백 함수를 익명 함수로 전달하는 과정이 반복되어 코드의 들여쓰기가 많이지는 현상
이를해결하기 위해서
promise + Async/await를 사용합니다.
const coffee = function(name){
return new Promise(function(resolve){
setTimeout(function(){
resolve(name)
}, 500)
})
}
const maker = async function(){
let coffeeList = ''
const addCoffee = async function(name){
coffeeList += (coffeeList ? ',':'') + await addCoffee(name)
}
await addCoffee('아메리카노')
console.log(coffeeList)
await addCoffee('카페라떼')
console.log(coffeeList)
await addCoffee('달고나라떼')
console.log(coffeeList)
await addCoffee('카페모카')
console.log(coffeeList)
}
maker()
728x90