promises (futures) Promises provide a simpler alternative for executing, composing, and managing asynchronous operations when compared to traditional callback-based approaches. They also allow you to handle asynchronous errors using approaches that are similar to synchronous try/catch. World Before Promises: CallbackMust we use promise for asynchronous call? Nope. Prior to Promise, we use callback. Callback is just a function you call when you get the return result. The syntax is less user friendly. In a nicer term, It looks like a pyramid, but people usually refer this as "callback hell", because the callback nested into another callback. Imagine you have 10 callbacks, your code will nested 10 times! JSON.stringify(myObj, null, 4) if(typeof myObj== "undefined" )
JavaScripts in the BODY section will be executed WHILE the page loads. JavaScripts in the HEAD section will be executed when CALLED.
Comments
UNTYPED: Variables are UNTYPED you can also redeclare or change the content of a variable to any data type.
Objects as |
alert <html> <head> <script type="text/javascript"> function show_alert() { alert("I am an alert box!"); } </script> </head> <body> <input type="button" onclick="show_alert()" value="Show alert box" /> </body> </html> | confirm <html> <head> <script type="text/javascript"> function show_confirm() { var r=confirm("Press a button"); if (r==true) document.write("You pressed OK!"); else document.write("You pressed Cancel!"); } </script> </head> <body> <input type="button" onclick="show_confirm()" value="Show confirm box" /> </body> </html> | prompt <html> <head> <script type="text/javascript"> function show_prompt() { var name=prompt("Please enter your name","Harry Potter"); if (name!=null && name!="") { document.write("Hello " + name + "! How are you today?"); } } </script> </head> <body> <input type="button" onclick="show_prompt()" value="Show a prompt box" /> </body> </html> |
return a*b;
Catch and handle JavaScript error messages, so you don't lose your audience. When users see errors, they often leave the Web page.
err can be a string, integer, Boolean or an object.try{throw "Err1";..}catch(er){if(er=="Err1"){}}
onload - onUnload: onload is used to check the browser type and version to display page properly. Often used to deal with cookies that should be set when a user enters or leaves a page.onFocus, onBlur and onChange: blur is when object loses focus.onSubmit: used to validate ALL form fields before submitting it.
<form method="post" action="xxx.htm" onsubmit="return checkForm()"> The function checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled.
onMouseOver - onMouseOut <a href="http://www.w3schools.com" onmouseover="alert('An onMouseOver event');return false"><img src="w3s.gif" alt="W3Schools" /></a>
if(!confirm(txt))
{
document.location.href="http://www.w3schools.com/";
}
Special Characters
\' single quote
\" double quote
\& ampersand
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed
Break Code LineYou can break up a code line within a text string with a backslash.
document.write("Hello \
World!");
Operators
.(property access) [](array index) ()(function arguments in function call) new(constructor call, create new object) ++(increment) --(decrement) -(negation) +(no-op) ~(bitwise complement) !(logical complement) delete(undefine a property) typeof(data type) void(return undefined value) +(plus) -(minus) *(multiply) /(devide) %(remainder) +(string concatenation) <<(bitwise left shift) >>(bitwise right shift with sign extension) >>>(bitwise right shift with zero extension) <(less than) <=(less than or equal) >(greater than) >=(greater than or equal) instanceof(check object type) in(check whether property exists) ==(equality) !=(inequality) ===(identity) !==(nonidentity) &(biwise AND) ^(biwise XOR) |(biwise OR) &&(logical AND) ||(logical OR) ?:(conditional operator) =(assignment) +=(assignment with operation) -= *= /= %= <<= >>= >>>= &= ^= |= ,(multiple evaluation)number, boolean, string, null, undefined, this, NAN, Infinity
Strings are immutable and passed by refernce to functions meanwhile non modifiable. On the other hand, strings are compared by value.
NAN, Infinity
Array
No multi-dimensional array. BUT elements of array can be any data type even arrays of various lengths.There can be undefined elements in an array, like var arr = [1,,,,5];
Defining an array:
var myCars=new Array("Saab","Volvo","BMW"); // condensed arrayvar myCars=["Saab","Volvo","BMW"]; // literal arrayvar myCars=new Array(); // regular array (add an optional integer argument to control array's size)myCars[0]="Saab";myCars[1]="Volvo";myCars[2]="BMW";
Methods
document.write(arr);parents.concat(children);arr.join(); //put all the elements of an array into a string.
arr.join(',');
arr.sort();
Boolean
var b1=new Boolean( 0);var b2=new Boolean(1);var b3=new Boolean("");var b4=new Boolean(null);var b5=new Boolean(NaN);var b6=new Boolean("false");document.write("0 is boolean "+ b1 +"<br />"); //0 is boolean falsedocument.write("1 is boolean "+ b2 +"<br />"); //1 is boolean truedocument.write("null is boolean "+ b4+ "<br />"); //null is boolean falsedocument.write("NaN is boolean "+ b5 +"<br />"); //NaN is boolean falsedocument.write("An empty string is boolean "+ b3 + "<br />"); //An empty string is boolean falsedocument.write("The string 'false' is boolean "+ b6 +"<br />"); //The string 'false' is boolean true
RegExp
test(): searches a string for a specified value. Returns true or falseexec(): searches a string for a specified value. Returns the text of the found value. If no match is found, it returns nullcompile() method is used to change the RegExp.can change both the search pattern, and add or remove the second parameter.
You can add a second parameter to the RegExp object, to specify your search. For example; if you want to find all occurrences of a character, you can use the "g" parameter ("global"). When using the "g" parameter, the exec() method works like this:* Finds the first occurence of "e", and stores its position* If you run exec() again, it starts at the stored position, and finds the next occurence of "e", and stores its position
var patt1=new RegExp("e");document.write(patt1.test("The best things in life are free"));
Date
var myDate=new Date();myDate.setDate(myDate.getDate()+5); // If adding five days to a date shifts the month or year, the changes are handled automatically by the Date object itself!
Objects are a collection of properties each of which consists of a name and a value. They are equal to a Java Map (or dictionary or hash) in concept.
Access Object Properties
ride.makeride['make']var p = 'make'; ride[p];
Object Creation Ways
1. Create Template of an Object
You can also add some methods to the person object. This is also done inside the template:function person(firstname,lastname,age,eyecolor){
this.firstname=firstname;this.lastname=lastname;this.age=age;this.eyecolor=eyecolor;this.newlastname=newlastname; //method
}function newlastname(new_lastname){
this.lastname=new_lastname;
}
myFather=new person("John","Doe",50,"blue"); myMother=new person("Sally","Rally",48,"green");
2. Incrementally Make an Arbitrary Object
var ride = new Object();ride.make = 'Yamaha';ride.model = 'V-Star Silverado 1100';ride.year = 2005;ride.purchased = new Date(2005,3,12);
3. Use JSON Notation (An Object Literal)
var ride = {
make: 'Yamaha',model: 'V-Star Silverado 1100',year: 2005,purchased: new Date(2005,3,12),owner: {
name: 'Spike Spiegel',occupation: 'bounty hunter'
}
};
null
undefinedaccess a variable that is not definedaccess a declared variable that is not initializednull==undefined, to distinguish use the === identity equity or typeof operator. E.g, my.pop == null --> true if my doesn't have a pop property or it is not initialized
this who owns that line of code that 'this' happens to be at? Default owner of a method is 'window'
method.call(onObj, param1, param2, param3, ...) method.apply(onObj, [param1, param2, param3, ...]) : run method as if it belongs to the obj in its parameter list
var Person = { name: "Tim",};
age: 28,
greeting: function () {
return "Hello " + this.name + ". Wow, you are " + this.age + " years old.";
}
Person.greeting();
var Alien = {name: "Zygoff",}
age: 5432
Person.greeting.call(Alien); // a new object that doesn't even have a greeting function, but can still be used by it. (inject the object Alien as the "this" value.)
Let's make a generic function that can work with any object that has age and name properties:function makeOlder(years, newname) {this.age += years;if (newname) {this.name = newname;}}
makeOlder.call(Person, 2, "Old Tim");
makeOlder.apply(Dog, [1, "Shaggy"]);
console.dir({Person: Person, Dog: Dog});
<html><head><title>Function Context Example</title><script>var o1 = {handle:'o1'};var o2 = {handle:'o2'};var o3 = {handle:'o3'};window.handle = 'window'; function whoAmI() {return this.handle;} o1.identifyMe = whoAmI; alert(whoAmI());alert(o1.identifyMe());alert(whoAmI.call(o2));alert(whoAmI.apply(o3)); </script></head> <body></body></html><html><head><title>Function Context Example</title><script>var o1 = {handle:'o1'};var o2 = {handle:'o2'};var o3 = {handle:'o3'};window.handle = 'window';function whoAmI() {return this.handle;}o1.identifyMe = whoAmI;alert(whoAmI());alert(o1.identifyMe());alert(whoAmI.call(o2));alert(whoAmI.apply(o3));</script></head><body></body></html>What is the result?The result is window, o1, o2, o3.the function acts like a method to o2, even though it has no association whatsoever—even as a property—with o2.
the function context is determined on a per invocation basis and that a single function can be called with any object acting as its context. It’s, therefore, probably never correct to say that a function is a method of an object. It’s much more correct to state:A function f acts as a method of object o when o serves as the function context of the invocation of f.
alert(o1.identifyMe.call(o3));The result is o3.further emphasizing that it’s not how a function is declared but how it’s invoked that determines its function context.
What is the value of this at line A? Why?<script type="text/javascript">if (true) {// Line A}</script>windowLine A is evaluated in the initial global execution context.What is the value of this at line B when obj.staticFunction() is executed? Why?<script type="text/javascript">var obj = {someData: "a string"};function myFun() {// Line B}obj.staticFunction = myFun;obj.staticFunction();</script>objWhen calling a function on an object, ThisBinding is set to the object.What is the value of this at line C? Why?<script type="text/javascript">var obj = {myMethod : function () {// Line C}};var myFun = obj.myMethod;myFun();</script>windowIn this example, the JavaScript interpreter enters function code, but because myFun/obj.myMethod is not called on an object, ThisBinding is set to window.This is different from Python, in which accessing a method (obj.myMethod) creates a bound method object.What is the value of this at line D? Why?<script type="text/javascript">function myFun() {// Line D}var obj = {myMethod : function () {eval("myFun()");}};obj.myMethod();</script>windowThis one was tricky. When evaluating the eval code, this is obj. However, in the eval code, myFun is not called on an object, so ThisBinding is set to window for the call.What is the value of this at line E?<script type="text/javascript">function myFun() {// Line E}var obj = {someData: "a string"};myFun.call(obj);</script>objThe line myFun.call(obj); is invoking the special built-in function Function.prototype.call(), which accepts thisArg as the first argument.
Function
Functions are objects in JavaScript. Can be:- Assigned to variables
- Assigned as a property of an object
- Passed as a parameter
- Returned as a function result
- Created using literals
It’s named only by references that are made to it.
Function instances are values that can be assigned to variables, properties, or parameters just like instances of other object types.And like those other object types, nameless disembodied instances aren’t of any use unless they’re assigned to a variable, property, or parameter through which they can be referenced.Although a function can be made to act like a method of an object by setting the object as the function context, functions aren’t declared as methods of any single object. The way a method is invoked and the closure of the variables it requires determine the actual context of execution which can be called by any object which in case can lead to totally different behaviors.
obj.fieldG = 5;func = function(myArgument){document.write(myArgument);}obj.field=func;obj.fieldG = func;obj.fieldG("sample argument"); //as if calling the functions code but with different name.
Primitive datatypes (number, boolean, String) passed by value.objects and arrays passed by reference.
prototype
javascript prototype property allows you to add properties and methods to an object.object.prototype.name=value
function employee(name,jobtitle,born){
this.name=name;this.jobtitle=jobtitle;this.born=born;
}var fred=new employee("Fred Flintstone","Caveman",1970);employee.prototype.salary=null;fred.salary=20000;
yield
Probably everybody knows about yield now, but some better documentation has come along. "Javascript's Future: Generators" by James Long has some good examples, including:
function foo(x) {while (true) {x = x * 2;yield x;}}"When you call foo, you get back a Generator object which has a next method."var g = foo(2);g.next(); // -> 4g.next(); // -> 8g.next(); // -> 16So yield is kind of like return: you get something back. return x returns the value of x, but yield x returns a function, which gives you a method to iterate toward the next value. Useful if you have a potentially memory intensive procedure that you might want to interrupt during the iteration.
promises
Events are great for things that can happen multiple times on the same object — keyup, touchstart etc. With those events you don't really care about what happened before you attached the listener.
promises
img1.ready().then(function() {// loaded}, function() {// failed});// and…Promise.all([img1.ready(), img2.ready()]).then(function() {// all loaded}, function() {// one or more failed});
At their most basic, promises are a bit like event listeners except:
- A promise can only succeed or fail once. It cannot succeed or fail twice, neither can it switch from success to failure or vice versa- If a promise has succeeded or failed and you later add a success/failure callback, the correct callback will be called, even though the event took place earlier
This is extremely useful for async success/failure, because you're less interested in the exact time something became available, and more interested in reacting to the outcome.
var promise = new Promise(function(resolve, reject) {
// do a thing, possibly async, then…
if (/* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
//Here's how you use that promise:
promise.then(function(result) {
console.log(result); // "Stuff worked!"
}, function(err) {
console.log(err); // Error: "It broke"
});
//example XMLHttpRequest get request
function get(url) {// Return a new promise.return new Promise(function(resolve, reject) {// Do the usual XHR stuffvar req = new XMLHttpRequest();req.open('GET', url);req.onload = function() {// This is called even on 404 etc// so check the statusif (req.status == 200) {// Resolve the promise with the response textresolve(req.response);}else {// Otherwise reject with the status text// which will hopefully be a meaningful errorreject(Error(req.statusText));}};// Handle network errorsreq.onerror = function() {reject(Error("Network Error"));};// Make the requestreq.send();});}//Now let's use it:get('story.json').then(function(response) {console.log("Success!", response);}, function(error) {console.error("Failed!", error);});
http://bahmutov.calepin.co/linking-promises.html