Skip to content

Instantly share code, notes, and snippets.

@thiagoh
Last active February 26, 2017 06:01
Show Gist options
  • Select an option

  • Save thiagoh/b7afa2a0cd77852797ddfbaf523348db to your computer and use it in GitHub Desktop.

Select an option

Save thiagoh/b7afa2a0cd77852797ddfbaf523348db to your computer and use it in GitHub Desktop.
/*
* This code was inspired by AngularJS $resource object
* on which you can do something like this:
var users = User.query(function() {
console.log(users[0]);
});
* Source code: https://github.com/angular/angular.js/blob/master/src/ngResource/resource.js#L76
*/
// something that, differently than other languages, you can easily reach with JS
var returnRefThenCall = function returnRefThenCall(callback) {
var value,
// create and execute the promise
p = new Promise(function(fullfill, reject) {
// execution phase 1
value = ['my', 'name', 'is', 'foo', 'bar'];
fullfill();
})
.then(function() {
// execution phase 3
callback();
});
// execution phase 2
// first return the value
return value;
};
// the array is returned
var array = returnRefThenCall(
// after returnAndCall returns it calls the callback function
// and by that time you already have the `array` set
function() {
console.log(array.join(','));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment