Skip to content

Instantly share code, notes, and snippets.

@mizdra
Last active May 24, 2016 05:55
Show Gist options
  • Save mizdra/684c7b9349b000ef092edd8e573084bd to your computer and use it in GitHub Desktop.
Save mizdra/684c7b9349b000ef092edd8e573084bd to your computer and use it in GitHub Desktop.
$(function(){
getModules().then(function(modules) {
// 全ての非同期通信が完了したらこの関数が実行される。
console.log(modules);
});
});
// 複数の非同期通信を実行し、全てが終了したら.thenをコールするPromise(jQuery.DeferredのPromise)を返す。
function getModules(){
// jQuery.Deferredを使い、jQueryでPromiseを扱う
// (jQuery.DeferredのPromiseはES2015 Promiseとは異なるjQuery独自のPromiseである。ES2015 Promiseと非常によく似た記法で非同期関数を書ける。)
var d = new $.Deferred();
// 非同期通信で得た結果を格納する配列
var results = [];
var count = 3;
function onFulfilled(value){
// 非同期通信で得た結果を格納
results.push(value);
if(results.length === count)
d.resolve(results);
}
// 以下は非同期通信を行う関数
// 本来は$.ajax().then(...).catch(...)のように例外処理もすべきであるが簡単のため省略
// ajax 1
$.ajax({
url: "module1.html"
}).then(onFulfilled);
// ajax 2
$.ajax({
url: "module2.html"
}).then(onFulfilled);
// ajax 3
$.ajax({
url: "module3.html"
}).then(onFulfilled);
// Promise likeなオブジェクト(then, catchメソッドを持つオブジェクト)を返す
return d.promise();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment