Last active
October 29, 2015 07:53
-
-
Save yuki-takeichi/481692ff6cad548fe441 to your computer and use it in GitHub Desktop.
Promise sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//sum([1,2,3]) == 6 | |
function sum3() { | |
var a = sum([1]); | |
var b = sum([1,2]); | |
var c = sum([1,2,3]); | |
return a + b + c; | |
} | |
function sum(nums) { | |
var cum = 0; | |
for (var i = 0; i < nums.length; i++) { | |
cum += nums[i]; | |
} | |
return cum; | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* sum([1,2,3]).then(function(res) { | |
* // res == 6 | |
* }); | |
*/ | |
function sum(nums) { | |
var promise = new Parse.Promise(); | |
setTimeout(500, function() { | |
var cum = 0; | |
for (var i = 0; i < nums.length; i++) { | |
cum += nums[i]; | |
} | |
promise.resolve(cum); | |
}); | |
return promise; | |
} | |
/* sum3().then(function(res) { | |
* // res == 6 | |
* }); | |
*/ | |
function sum3() { | |
return sum([1]).then(function(a) { | |
return Parse.Promise.as(a, [1,2]); | |
}).then(function(a, hoge) { | |
return sum(hoge).then(function(b) { | |
return Parse.Promise.as(a, b, [1,2,3]); | |
}); | |
}).then(function(a, b, hoge) { | |
return sum(hoge).then(function(c) { | |
return Parse.Promise.as(a+b+c); | |
}); | |
}); | |
} | |
function sum3_2() { | |
var promises = [ sum([1]), sum([1,2]), sum([1,2,3]) ]; | |
return Parse.Promise.when(promises, function(a,b,c) { | |
return Parse.Promise.as(a+b+c); | |
}); | |
} | |
function sum3_3() { | |
var a_, b_; | |
return sum([1]).then(function(a) { | |
a_ = a; | |
return sum([1,2]); | |
}).then(function(b) { | |
b_ = b; | |
//a_ = 'hogehoge'; | |
return sum([1,2,3]); | |
}).then(function(c) { | |
return Parse.Promise.as(a_+b_+c); | |
}); | |
} | |
function sum3_4() { | |
return sum([1]).then(function(a) { | |
return sum([1,2]).then(function(b) { | |
return sum([1,2,3]).then(function(c) { | |
return Parse.Promise.as(a+b+c); | |
}); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment