Skip to content

Instantly share code, notes, and snippets.

@hoony-o-1
Created November 14, 2017 13:10
Show Gist options
  • Save hoony-o-1/f3a4958865fc53cc09897ff2c05e9fb8 to your computer and use it in GitHub Desktop.
Save hoony-o-1/f3a4958865fc53cc09897ff2c05e9fb8 to your computer and use it in GitHub Desktop.
Callback & Promise
// 1. Great!
for (var i = 0; i < 10; i++) {
console.log(i);
}
console.log('done');
// 2. Stupid!
for (var i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i);
}, 10)
}
console.log('done');
// 1. async
const fs = require('fs')
fs.readFile('/file.md', (err, data) => {
if (err) throw err
console.log(data)
})
// 2. blocking
const fs = require('fs')
const data = fs.readFileSync('/file.md')
console.log(data)
function getDataFromApi (id, callback) {
setTimeout(() => {
const data = []
callback(null, data)
}, 500)
}
// 1. callback
getDataFromApi(1, function (err, data) {
if (err) {
//
} else {
//
}
})
// 2. callback hell
getDataFromApi(1, function (err, data1) {
getDataFromApi(2, function (err, data2) {
getDataFromApi(3, function (err, data3) {
getDataFromApi(4, function (err, data4) {
// ?????
})
})
})
})
// 1. Promise
function getDataFromApi (id) {
return new Promise(function (resolve, reject) {
setTimeout(() => {
const data = []
resolve(data1)
// err?
// reject(new Error('에러가 발생했습니다.'))
}, 1000)
})
}
// 2. Series
// - 필요한 요청에 대한 순서를 보장하기에 명확하고 코드의 가독성이 보다 간결해진다.
// - 다음 Promise로 넘기기 위해서는 Promise 혹은 유의미한 값을 return 하면 된다.
// - 에러를 반환하기 위해서는 부정적인 값 혹은 Error 객체를 return 하거나 throw 하면 된다.
getDataFromApi(1)
.then(function (data1) {
return getDataFromApi(2)
})
.then(function (data2) {
return getDataFromApi(3)
})
.then(function (data3) {
return getDataFromApi(4)
// return new Error('data3을 처리하는 과정에서 에러가 발생했습니다.')
})
.then(function (data4) {
})
.catch(function (err) {
})
// 3. All
// - 4개의 Promise 중 순서를 보장하지 않고 요청을 보내며 대신 결과값은 순서를 보장한 배열에 담겨 들어온다.
// - 4개의 Promise 중 어느 하나라도 실패한 경우 해당 에러가 담겨 .catch 로 넘어간다.
Promise.all([
getDataFromApi(1),
getDataFromApi(2),
getDataFromApi(3),
getDataFromApi(4)
])
.then(function (result) {
// result = [data1, data2, data3, data4]
})
.catch(function (err) {
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment