Promise async a = async function() {return 1} b = a() // Promise catchで例外を取得することを忘れない var p = new Promise(function(resolve, reject) { setTimeout(resolve, 500, "start"); }); p.then(v => v).then(v => console.log(v)); // => start Promiseでresolveとrejectを交互に実行する。 var p = new Promise(function(resolve, reject) { setTimeout(resolve, 500, "start"); }); p.then( function(v) { console.log(v); return Promise.reject("a"); }, function(v) { console.log(v); return Promise.reject("A"); } ).then( function(v) { console.log(v); return Promise.reject("b"); }, function(v) { console.log(v); return Promise.resolve("B"); } ).then( function(v) { console.log(v); return Promise.reject("c"); }, function(v) { console.log(v); return Promise.reject("C"); } ).then( function(v) { console.log(v); return Promise.reject("d"); }, function(v) { console.log(v); return Promise.reject("D"); } ); Promiseで非同期の処理を連続で実行する。 var p = new Promise(function(resolve, reject) { setTimeout(resolve, 6000, "one"); }); p.then( function(v) { console.log(v); return new Promise(function(resolve, reject) { setTimeout(resolve, 1000, "two"); }); } ).then( function(v) { console.log(v); return new Promise(function(resolve, reject) { setTimeout(resolve, 1, "three"); }); } ).then( function(v) { console.log(v); } ); 複数のPromiseを1つにまとめる var p1 = new Promise(function(resolve, reject) { setTimeout(resolve, 1000, "11111"); }); var p2 = new Promise(function(resolve, reject) { setTimeout(resolve, 100, "22222"); }); var p3 = new Promise(function(resolve, reject) { setTimeout(resolve, 1500, "33333"); }); Promise.all([p1, p2, p3]).then(function(values) { // ["11111", "22222", "33333"] console.log(values); }); var p4 = new Promise(function(resolve, reject) { setTimeout(resolve, 2000, "aaaaa"); }); var p5 = new Promise(function(resolve, reject) { setTimeout(reject, 2600, "bbbbb"); }); var p6 = new Promise(function(resolve, reject) { setTimeout(resolve, 200, "ccccc"); }); Promise.all([p4, p5, p6]).then(function(values) { console.log(values); }, function(values) { // bbbbb console.log(values); }); catchを使用する var p = new Promise(function(resolve, reject) { setTimeout(resolve, 500, "start"); }); p.then(function(v) { console.log("A"); console.log(v); return Promise.reject("a"); }).then(function(v) { console.log("B"); console.log(v); return Promise.resolve("b"); }).catch(function(v) { console.log("C") console.log(v); }); //A //start //C //a 一番早く結果が出たものを使用する var p1 = new Promise(function(resolve, reject) { setTimeout(resolve, 1500, "A"); }); var p2 = new Promise(function(resolve, reject) { setTimeout(resolve, 1000, "B"); }); var p3 = new Promise(function(resolve, reject) { setTimeout(resolve, 2000, "C"); }); Promise.race([p1, p2, p3]).then(function(v) { console.log(v); }); //B