public
Created

promises

  • Download Gist
1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// ajax call with async callback
// -----------------------------
$.ajax({
type: "GET",
url: "/foo",
 
success: function(data){
// this is a callback, used for the async result
}
 
});
 
// DOM event handler with a callback
// ---------------------------------
$("#some-element").click(function(e){
// this is a callback for the element click
});
2.js
JavaScript
1 2 3 4 5 6 7 8 9
function doSomeStuff(callback){
// do some processing here
var foo = getBar();
 
// call the callback, passing in a variable
callback(foo);
 
// do some more processing here if needed
}
3.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11
doSomething(function(foo){
foo = processFoo(foo);
doMoreStuff(foo, function(bar){
var baz = getBaz(foo);
stillMore(baz, function(quux){
gettingPrettyBad(function(widget){
return widget + baz;
});
});
});
});
4.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11
function doSomething(){
var promise = new Promise();
 
// ... do async stuff here
asyncFoo(function(){
// resolve the promise
promise.complete();
});
 
return promise;
}
5.js
JavaScript
1 2 3 4 5
var promise = doSomething();
 
promise.then(function(foo){
// continue working here
});
6.js
JavaScript
1 2 3
args.setPromise(WinJS.UI.processAll().then(function () {
// ...
}
7.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
return new WinJS.Promise(function (complete, error, progress) {
 
applicationData.current.localFolder.createFolderAsync(thumbnailFolderName, creationCollisionOption.replaceExisting)
.then(function (folder) {
 
var localThumbnail = 'ms-appdata:///local/' + thumbnailFolderName + '/';
 
var promises = files.map(function (fileInfo) {
var createFile = folder.createFileAsync(fileInfo.name, creationCollisionOption.replaceExisting);
return createFile.then(function (newFile) {
 
return newFile.openAsync(Windows.Storage.FileAccessMode.readWrite).then(function (output) {
var input = fileInfo.thumbnail.getInputStreamAt(0);
 
return randomAccessStream.copyAsync(input, output).then(function () {
return output.flushAsync().then(function () {
input.close();
output.close();
return fileInfo.name;
});
});
});
});
});
 
WinJS.Promise.join(promises).then(function (files) {
var paths = files.map(function (file) {
return localThumbnail + file;
});
complete(paths);
});
 
});
});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.