Skip to content

Instantly share code, notes, and snippets.

@crongro
Created February 27, 2014 04:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crongro/9244445 to your computer and use it in GitHub Desktop.
Save crongro/9244445 to your computer and use it in GitHub Desktop.
Promise pattern
/* json
{
"sum" : "68",
"majors" : [
{
"count" : "12",
"url" : ["../jisu.json","../jisu2.json","../jisu3.json","../jisu4.json"],
"professor" : "younJisu"
},
{
"count" : "12",
"name" : "WEB SERVER",
"professor" : "javarigi"
}
]
}
*/
<html>
<head>
</head>
<body>
<input type="button" onclick="runPromise();" value="promise"/>
<input type="button" onclick="runPromiseArray();" value="promiseWithArray"/>
</body>
<script>
function xhr_promise(url) {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
if (req.status == 200) {
// 응답 텍스트로 promise를 해결(resolve)합니다.
resolve(req.responseText);
} else {
// 상태 텍스트와 함께 거부(reject)합니다.
reject(Error(req.statusText));
}
};
req.onerror = function() {
reject(Error("Network Error"));
};
req.send();
});
}
var oP = null;
function runPromise() {
//oP 객체를 저장해 둔다.
oP = oP || xhr_promise('../response2.json');
oP.then(function(res) {
return JSON.parse(res);
}).then(function(res) {
return xhr_promise(res.majors[0].url);
}).then(function(res){
console.log('res', res.wife);
}, function(err) {
console.log('error -> ' , err.message);
throw new Error("error occured!");
}).then(function() {
console.log("finished"); //이때는 error 를 포함해서 항상 불린다. 하지만 이 에제에서는 위에 throw error를 했기때문에 아래 catch로 이동하게 됐다.
}).catch(function(e) {
console.log("finally error occured : ", e.message); //위에서 throw한 결과이렇게 됐음.
});
}
function runPromiseArray() {
oP = oP || xhr_promise('../response2.json');
// oP.then(function(res) {
// return JSON.parse(res);
// }).then(function(res) {
// res.majors[0].url.forEach(function(v,i,o) {
// //return xhr_promise(v);
// xhr_promise(v).then(function() {
// console.log("success url -> ", v); // 사이즈가 큰 json2파일은 나중에 로딩
// })
// });
// //return을 하면 아래 코드로 한 번만 안넘어간다.
// });
//두번째 방법
oP.then(function(res) {
return JSON.parse(res);
}).then(function(res) {
var sequence = Promise.resolve();
res.majors[0].url.forEach(function(v,i,o) {
sequence = sequence.then(function() {
return xhr_promise(v);
}).then(function() {
console.log("success url -> ", v); // 사이즈가 큰 json2파일이 있지만 순서가 지켜짐
})
});
})
}
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment