Skip to content

Instantly share code, notes, and snippets.

View josescasanova's full-sized avatar
:octocat:

jose josescasanova

:octocat:
View GitHub Profile
var a = "mystring",
b = new String( "mystring" );
Object.defineProperty( b, 'foo', { value: 42, enumerable: false });
console.log(b.foo); // 42
Object.defineProperty( a, 'foo', { value: 42, enumerable: false });
// TypeError: Object.defineProperty called on non-object
// trying another way:
a.foo = 42;
// remember, this is equivalent to:
// new Number(a).foo = 42;
"foobar".big();
// is equivalent to
new String("foobar").big();
3.14.toFixed();
// is equivalent to
new Number(3.14).toFixed();
var a = function() {},
b = function b() {},
c = function foo() {};
function d() {}
alert(a.name); // ""
alert(b.name); // "b"
alert(c.name); // "foo"
alert(d.name); // "d"
(3.14).toFixed(); // "3"
3.14.toFixed(); // "3"
(3).toFixed(); // "3"
3.toFixed(); // SyntaxError: Unexpected token ILLEGAL
3..toFixed(); // "3"
var n = 42;
function f() { alert("foo"); };
alert("n is " + n.toString()); // "n is 42"
alert(f.name + " is a function"); // "f is a function"
getSomeDataFromGoogle()
.then(getSomeThingFromTwitter())
.then(saveSomethingToStorage())
.then(displayInfoToUsers(),
function errorHandler(err) {
console.log('You only need to handle error this once in the whole chain.');
});
defered.then(
function successHandler(id) {
console.log('Object saved, with id: ', id);
},
function errorHandler(error) {
console.log('Error saving object: ', error);
});
var defered = promiseBasedSave({name: 'John Doe'});
function promiseBasedSave(inputData) {
// FIRST: you need to setup some state.
var state = 'pending';
var callbacks = [];
var errorCallbacks = [];
var value; // this is what we will finally resolve
var error; // if any
var promise = {
then: function(callback, errorCallback) {
// you need to save the callback, the error callback
$.ajax({
url: 'http:\/\/www.google.com/search?q=what is javascript promise',
type: 'GET',
success: function(data, status, xhr) {
alert('Response from Google: ' + data.toString());
},
error: function(xhr, status, error) {
alert('Error in request ' + error && error.toString());
}
});