chrome.storage
API를 사용하면서 코드를 동기적으로 처리할 때가 발생한다.
chrome.storage
는 콜백 함수를 제공하는데 이걸 남발하면 엄청 복잡해진다..
chrome.storage.local.get("count", function(count) {
let sourceCount = count.count
chrome.storage.local.get("sources", function(sources) {
let sourceAll = sources.sources
chrome.storage.local.get("node", function(node) {
let sourceNode = node.node
sourceMix(sourceCount,sourceAll,sourceNode)
});
});
});
이런식으로 chrome.storage
의 콜백 함수안에 계속해서 콜백함수를 넣어서 동기화 한다면 가독성도 떨어지고, 유지보수도 매우 힘들다. 그렇기 때문에 이 코드를 async&await와 promise를 사용해서 바꾸어 보자.
async function getCount(){
let c = new Promise(function(resolve, reject){
chrome.storage.local.get("count", function(count) {
resolve(count.count);
})
});
let count = await c
return count
}
이런 형태로 async function을 만들고 그 안에서 promise 객체를 생성하여 값을 반환 받는다.
이렇게 count와 sources, node를 분리해서 aync function을 만들어 준다면
(async function fetchSource(){
let sourceCount = await getCount()
let sourceAll = await getSources()
let sourceNode = await getNode()
sourceMix(sourceCount,sourceAll,sourceNode)
}())
이렇게 바꿀 수 있다.
async&await 와 promise를 사용하니 메인 로직을 보기 아주 편--안 해졌다.