You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ignite.apache.org by iv...@apache.org on 2015/07/14 13:45:59 UTC

[1/3] incubator-ignite git commit: #ignite-961: rewrite compute-tests.

Repository: incubator-ignite
Updated Branches:
  refs/heads/ignite-961-promise 0479f5b42 -> 341f30310


#ignite-961: rewrite compute-tests.


Project: http://git-wip-us.apache.org/repos/asf/incubator-ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-ignite/commit/88bb97d6
Tree: http://git-wip-us.apache.org/repos/asf/incubator-ignite/tree/88bb97d6
Diff: http://git-wip-us.apache.org/repos/asf/incubator-ignite/diff/88bb97d6

Branch: refs/heads/ignite-961-promise
Commit: 88bb97d69aef4adc7f327b5c9af25b3062efa1d9
Parents: 0479f5b
Author: ivasilinets <iv...@gridgain.com>
Authored: Tue Jul 14 13:51:04 2015 +0300
Committer: ivasilinets <iv...@gridgain.com>
Committed: Tue Jul 14 13:51:04 2015 +0300

----------------------------------------------------------------------
 modules/nodejs/src/main/js/compute.js      |  36 +-
 modules/nodejs/src/test/js/test-compute.js | 814 ++++++++++++------------
 2 files changed, 415 insertions(+), 435 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/88bb97d6/modules/nodejs/src/main/js/compute.js
----------------------------------------------------------------------
diff --git a/modules/nodejs/src/main/js/compute.js b/modules/nodejs/src/main/js/compute.js
index 5c28418..53cd11c 100644
--- a/modules/nodejs/src/main/js/compute.js
+++ b/modules/nodejs/src/main/js/compute.js
@@ -31,11 +31,10 @@ function Compute(server) {
  * @this {Compute}
  * @param job Function
  * @param args Function arguments
- * @param {onGet} callback Callback
  */
-Compute.prototype.run = function(job, args, callback) {
-    this._server.runCommand(new Command("runscript").addParam("func", job).
-        setPostData(JSON.stringify({"arg" : args})), callback);
+Compute.prototype.run = function(job, args) {
+    return this._createPromise(new Command("runscript").addParam("func", job).
+        setPostData(JSON.stringify({"arg" : args})));
 }
 
 /**
@@ -46,11 +45,10 @@ Compute.prototype.run = function(job, args, callback) {
  * @param {string|number|JSONObject} key Key.
  * @param job Function
  * @param args Function arguments
- * @param {onGet} callback Callback
  */
-Compute.prototype.affinityRun = function(cacheName, key, job, args, callback) {
-    this._server.runCommand(new Command("affrun").addParam("func", job).addParam("cacheName", cacheName).
-        setPostData(JSON.stringify({"arg" : args, "key" : key})), callback);
+Compute.prototype.affinityRun = function(cacheName, key, job, args) {
+    return this._createPromise(new Command("affrun").addParam("func", job).addParam("cacheName", cacheName).
+        setPostData(JSON.stringify({"arg" : args, "key" : key})));
 }
 
 /**
@@ -61,14 +59,26 @@ Compute.prototype.affinityRun = function(cacheName, key, job, args, callback) {
  * @param {onGet} callback Callback
  */
 Compute.prototype.mapReduce = function(map, reduce, arg, callback) {
-    var command = new Command("excmapreduce");
-
-    command.addParam("map", map).addParam("reduce", reduce);
-    command.setPostData(JSON.stringify({"arg" : arg}));
+    var cmd = new Command("excmapreduce").addParam("map", map).addParam("reduce", reduce).
+        setPostData(JSON.stringify({"arg" : arg}));
 
-    this._server.runCommand(command, callback);
+    return this._createPromise(cmd);
 }
 
+
+Compute.prototype._createPromise = function(cmd) {
+    var server = this._server;
+    return new Promise(function(resolve, reject) {
+        server.runCommand(cmd, function(err, res) {
+            if (err != null) {
+                reject(err);
+            }
+            else {
+                resolve(res);
+            }
+        });
+    });
+}
 /**
  * @name EmitFunction
  * @function

http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/88bb97d6/modules/nodejs/src/test/js/test-compute.js
----------------------------------------------------------------------
diff --git a/modules/nodejs/src/test/js/test-compute.js b/modules/nodejs/src/test/js/test-compute.js
index 5cdc3e0..600f11d 100644
--- a/modules/nodejs/src/test/js/test-compute.js
+++ b/modules/nodejs/src/test/js/test-compute.js
@@ -23,28 +23,222 @@ var CacheEntry = Ignite.CacheEntry;
 var assert = require("assert");
 
 testComputeRunScript = function() {
-    TestUtils.startIgniteNode(onStart.bind(null, computeRunScript));
+    TestUtils.startIgniteNode().then(function(ignite) {
+        var cache = ignite.cache("mycache");
+
+        cache.putAll(getEntries()).then(function(res) {
+            var comp = ignite.compute();
+
+            var f = function (args) {
+                print("!!!!" + args + " " + ignite.name());
+                return args + " " + ignite.name();
+            }
+
+            return comp.run(f, "GridGain");
+        }).then(function(res) {
+            assert(res.indexOf("NodeJsComputeSelfTest") !== -1, "Incorrect result message. [mes=" + res + "].");
+            assert(res.indexOf("GridGain") !== -1, "Incorrect result message. [mes=" + res + "].");
+
+            TestUtils.testDone();
+        }).catch(function (err) {
+            assert(err === null, err);
+        })
+    }).catch(function(err) {
+        assert(err === null, err);
+    })
 }
 
 testComputeExecute = function() {
-    TestUtils.startIgniteNode(computeExecute);
+    TestUtils.startIgniteNode().then(function(ignite) {
+        var cache = ignite.cache("mycache");
+
+        cache.putAll(getEntries()).then(function(res) {
+            var map = function(nodes, arg) {
+                var words = arg.split(" ");
+
+                for (var i = 0; i < words.length; i++) {
+                    var f = function (word) {
+                        print(">>> Printing " + word);
+
+                        return word.length;
+                    };
+
+                    emit(f, words[i], nodes[i %  nodes.length]);
+                }
+            };
+
+            var reduce = function(results) {
+                var sum = 0;
+
+                for (var i = 0; i < results.length; ++i) {
+                    sum += results[i];
+                }
+
+                return sum;
+            };
+
+            return ignite.compute().mapReduce(map, reduce, "Hi Alice");
+        }).then(function(res) {
+            assert.equal(res, 7);
+
+            TestUtils.testDone();
+        }).catch(function (err) {
+            assert(err === null, err);
+        })
+    }).catch(function(err) {
+        assert(err === null, err);
+    })
 }
 
 testComputeAllNodeExecute = function() {
-    TestUtils.startIgniteNode(computeAllNodeExecute);
+    TestUtils.startIgniteNode().then(function(ignite) {
+        var cache = ignite.cache("mycache");
+
+        cache.putAll(getEntries()).then(function(res) {
+            var map = function(nodes, arg) {
+                for (var i = 0; i < nodes.length; i++) {
+                    var f = function (node) {
+                        print(">>> Printing " + node.id().toString());
+
+                        return "";
+                    };
+
+                    emit(f, nodes[i %  nodes.length], nodes[i %  nodes.length]);
+                }
+            };
+
+            var reduce = function(results) {};
+
+            return ignite.compute().mapReduce(map, reduce, "");
+        }).then(function(res) {
+            TestUtils.testDone();
+        }).catch(function (err) {
+            assert(err === null, err);
+        })
+    }).catch(function(err) {
+        assert(err === null, err);
+    })
 }
 
 testComputeCacheSizeExecute = function() {
-    TestUtils.startIgniteNode(computeCacheSizeExecute);
+    TestUtils.startIgniteNode().then(function(ignite) {
+        var cache = ignite.cache("mycache");
+
+        cache.put("key", "val").then(function(res) {
+            var map = function(nodes, arg) {
+                for (var i = 0; i < nodes.length; i++) {
+                    var f = function (args) {
+                        print("!!!!!Node id " + ignite.localNode().id());
+
+                        return ignite.cache("mycache").localSize();
+                    };
+
+                    emit(f, [1, 2], nodes[i]);
+                }
+            };
+
+            var reduce = function(results) {
+                var sum = 0;
+
+                for (var i = 0; i < results.length; i++) {
+                    sum += results[i];
+                }
+
+                return sum;
+            };
+
+            return ignite.compute().mapReduce(map, reduce, "");
+        }).then(function(res) {
+            console.log("Result=" + res);
+
+            TestUtils.testDone();
+        }).catch(function (err) {
+            assert(err === null, err);
+        })
+    }).catch(function(err) {
+        assert(err === null, err);
+    })
 }
 
 testComputeCacheExecute = function() {
-    TestUtils.startIgniteNode(computeCacheExecute);
+    TestUtils.startIgniteNode().then(function(ignite) {
+        var cache = ignite.cache("mycache");
+
+        entries = [];
+
+        var key1 = {"name" : "Ann"};
+        var key2 = {"name" : "Paul"};
+        var val1 = {"age" : 12, "books" : ["1", "Book"]};
+        var val2 = {"age" : 13, "books" : ["1", "Book"]};
+
+        entries.push(new CacheEntry(key1, val1));
+        entries.push(new CacheEntry(key2, val2));
+
+        cache.putAll(entries).then(function(res) {
+            var map = function(nodes, args) {
+                for (var i = 0; i < 1; i++) {
+                    var f = function (args1) {
+                        ignite.cache("mycache").put({"1": "1"},  2);
+
+                        var val = ignite.cache("mycache").get({"1": "1"});
+
+                        if (val !== 2) {
+                            throw "Incorrect return val [expected=2, val=" + val + "]";
+                        }
+
+                        var val1 = ignite.cache("mycache").get(args1.get(0));
+
+                        if (val1["age"] !== 12) {
+                            throw "Incorrect age [expected=12, val=" + val + "]";
+                        }
+
+                        print("BOOKS=" + val1.books);
+
+                        if (val1.books.length !== 2) {
+                            throw "Incorrect books length [expected=2, val=" +
+                                val1.books.length + "]";
+                        }
+
+                        if (val1.books[0] !== "1") {
+                            throw "Incorrect books value [expected=1, val=" +
+                                val1.books[0] + "]";
+                        }
+                        if (val1.books[1] !== "Book") {
+                            throw "Incorrect books value [expected=Book, val=" +
+                                val1.books[1] + "]";
+                        }
+
+                        return val1;
+                    };
+
+                    emit(f, args, nodes[i]);
+                }
+            };
+
+            var reduce = function(results) {
+                return {"1" : 1};
+            };
+
+            return ignite.compute().mapReduce(map, reduce, [key1, val1]);
+        }).then(function(res) {
+            assert(TestUtils.compareObject({"1": 1}, res),
+                "Incorrect result [exp= {1:1}, val=" + res);
+
+            return cache.size();
+        }).then(function(size){
+            assert(size === 3, "Incorrect size [size=" + 3 + ", res=" + size + "]");
+            TestUtils.testDone();
+        }).catch(function (err) {
+            assert(err === null, err);
+        })
+    }).catch(function(err) {
+        assert(err === null, err);
+    })
 }
 
 testComputeRunScriptContainsKey = function() {
-    function computeRunScriptContainsKey(error, ignite) {
-        assert(error == null, "Error on start:" + error);
+    TestUtils.startIgniteNode().then(function(ignite) {
+        var initKey = {"1" : ["1", "2"]};
 
         var comp = ignite.compute();
 
@@ -58,28 +252,25 @@ testComputeRunScriptContainsKey = function() {
             return key;
         }
 
-        function onEnd(err, res) {
-            assert(err == null);
-            assert(TestUtils.compareObject(initKey, res), "Incorrect result after script.")
-
-            ignite.cache("mycache").containsKey(initKey, function(err0, res0) {
-                assert(err0 === null, "Get error on js contatins key [err=" + err0 + "]");
-                assert(res0 === true, "Incorrect value on js contains key [res=" + res0 + "]");
-                TestUtils.testDone();
-            });
-        }
-
-        var initKey = {"1" : ["1", "2"]};
+        comp.run(f, initKey).then(function(res) {
+            assert(TestUtils.compareObject(initKey, res), "Incorrect result after script.");
 
-        comp.run(f, initKey, onEnd.bind(null));
-    }
+            return ignite.cache("mycache").containsKey(initKey);
+        }).then(function(res) {
+            assert(res === true, "Incorrect value on js contains key [res=" + res + "]");
 
-    TestUtils.startIgniteNode(computeRunScriptContainsKey);
+            TestUtils.testDone();
+        }).catch(function(err) {
+            assert(err === null, err);
+        })
+    }).catch(function(err) {
+        assert(err === null, err);
+    })
 }
 
 testComputeAffinityRunScriptContainsKey = function() {
-    function computeRunScriptContainsKey(error, ignite) {
-        assert(error == null, "Error on start:" + error);
+    TestUtils.startIgniteNode().then(function(ignite) {
+        var initKey = {"1" : ["1", "2"]};
 
         var comp = ignite.compute();
 
@@ -93,28 +284,26 @@ testComputeAffinityRunScriptContainsKey = function() {
             return key;
         }
 
-        function onEnd(err, res) {
-            assert(err == null, err);
-            assert(TestUtils.compareObject(initKey, res), "Incorrect result after script.")
-
-            ignite.cache("mycache").containsKey(initKey, function(err0, res0) {
-                assert(err0 === null, "Get error on js contatins key [err=" + err0 + "]");
-                assert(res0 === true, "Incorrect value on js contains key [res=" + res0 + "]");
-                TestUtils.testDone();
-            });
-        }
-
-        var initKey = {"1" : ["1", "2"]};
+        comp.affinityRun("mycache", initKey, f, initKey).then(function(res) {
+            assert(TestUtils.compareObject(initKey, res), "Incorrect result after script.");
 
-        comp.affinityRun("mycache", initKey, f, initKey, onEnd.bind(null));
-    }
+            return ignite.cache("mycache").containsKey(initKey);
+        }).then(function(res) {
+            assert(res === true, "Incorrect value on js contains key [res=" + res + "]");
 
-    TestUtils.startIgniteNode(computeRunScriptContainsKey);
+            TestUtils.testDone();
+        }).catch(function(err) {
+            assert(err === null, err);
+        })
+    }).catch(function(err) {
+        assert(err === null, err);
+    })
 }
 
 testComputeRunScriptContainsKeys = function() {
-    function computeRunScriptContainsKey(error, ignite) {
-        assert(error == null, "Error on start:" + error);
+    TestUtils.startIgniteNode().then(function(ignite) {
+        var initKey0 = {"1" : ["1", "2"]};
+        var initKey1 = {"2" : "AAA"};
 
         var comp = ignite.compute();
 
@@ -129,29 +318,29 @@ testComputeRunScriptContainsKeys = function() {
             return keys;
         }
 
-        function onEnd(err, res) {
-            assert(err == null);
+        comp.run(f, [initKey0, initKey1]).then(function(res) {
             assert(TestUtils.compareObject([initKey0, initKey1], res), "Incorrect result after script.")
 
-            ignite.cache("mycache").containsKey(initKey0, function(err0, res0) {
-                assert(err0 === null, "Get error on js contatins key [err=" + err0 + "]");
-                assert(res0 === true, "Incorrect value on js contains key [res=" + res0 + "]");
-                TestUtils.testDone();
-            });
-        }
+            return ignite.cache("mycache").containsKey(initKey0);
+        }).then(function(res) {
+            assert(res === true, "Incorrect value on js contains key [res=" + res + "]");
 
-        var initKey0 = {"1" : ["1", "2"]};
-        var initKey1 = {"2" : "AAA"};
-
-        comp.run(f, [initKey0, initKey1], onEnd.bind(null));
-    }
-
-    TestUtils.startIgniteNode(computeRunScriptContainsKey);
+            TestUtils.testDone();
+        }).catch(function(err) {
+            assert(err === null, err);
+        })
+    }).catch(function(err) {
+        assert(err === null, err);
+    })
 }
 
 testComputeRunScriptPutAllGetAll = function() {
-    function computeRunScriptPutAllGetAll(error, ignite) {
-        assert(error == null, "Error on start:" + error);
+    TestUtils.startIgniteNode().then(function(ignite) {
+        var initKey0 = {"1" : ["1", "2"]};
+        var initKey1 = {"2" : "AAA"};
+        var initVal0 = {"1" : ["1", "2"]};
+        var initVal1 = {"2" : "AAA"};
+        var initEntries = [new CacheEntry(initKey0, initVal0), new CacheEntry(initKey1, initVal1)];
 
         var comp = ignite.compute();
 
@@ -163,281 +352,121 @@ testComputeRunScriptPutAllGetAll = function() {
             return cache.getAll(args[1]);
         }
 
-        function onEnd(err, res) {
-            assert(err == null);
-
+        comp.run(f, [initEntries, [initKey0, initKey1]]).then(function(res) {
             assert(TestUtils.compareObject(initEntries[0].key, res[0].key), "Incorrect result after script " +
                 "[InitEntries=" + JSON.stringify(initEntries[0].key) + ", val=" + JSON.stringify(res[0].key) + "]");
 
-            ignite.cache("mycache").containsKey(initKey0, function(err0, res0) {
-                assert(err0 === null, "Get error on js contatins key [err=" + err0 + "]");
-                assert(res0 === true, "Incorrect value on js contains key [res=" + res0 + "]");
-                TestUtils.testDone();
-            });
-        }
+            return ignite.cache("mycache").containsKey(initKey0);
+        }).then(function(res) {
+            assert(res === true, "Incorrect value on js contains key [res=" + res + "]");
 
-        var initKey0 = {"1" : ["1", "2"]};
-        var initKey1 = {"2" : "AAA"};
-        var initVal0 = {"1" : ["1", "2"]};
-        var initVal1 = {"2" : "AAA"};
-        var initEntries = [new CacheEntry(initKey0, initVal0), new CacheEntry(initKey1, initVal1)];
-
-        comp.run(f, [initEntries, [initKey0, initKey1]],
-            onEnd.bind(null));
-    }
-
-    TestUtils.startIgniteNode(computeRunScriptPutAllGetAll);
+            TestUtils.testDone();
+        }).catch(function(err) {
+            assert(err === null, err);
+        })
+    }).catch(function(err) {
+        assert(err === null, err);
+    })
 }
 
 testComputeRunScriptRemoveOperations = function() {
-    computeRunScriptRemoveOperations = function(error, ignite) {
-        assert(error === null, "Error on put:" + error);
-
-        var comp = ignite.compute();
-
-        var f = function (args) {
-            var cache = ignite.cache("mycache");
-
-            if (cache.remove("key1") === true) {
-                throw "Incorrect remove from empty map";
-            }
-
-            var key0 = {"keyName" : "keyVal"};
-            var key1 = {"keyName" : "keyVal1"};
-            var val0 = {"valName" : 1};
-            var val1 = {"valName" : 2};
-
-            var entries = [new CacheEntry(key0, val0), new CacheEntry(key1, val1)];
-            var keys = [key0, key1];
-
-            cache.put(key0, val0);
-
-            if (cache.removeValue(key0, val1) === true) {
-                throw "Incorrect removeValue from empty map [key=" + JSON.stringify(key0) + "]";
-            }
-
-            if (cache.remove(key0) === false) {
-                throw "Incorrect remove from empty map [key=" + JSON.stringify(key0) + "]";
-            }
-
-            cache.put(key0, val0);
-
-            if (cache.replaceValue(key0, val0, val1) === true) {
-                throw "Incorrect replaceValue result [key=" + JSON.stringify(key0) + "]";
-            }
-
-            var prevVal = cache.getAndReplace(key0, val1);
-
-            if (prevVal.valName !== val0.valName) {
-                throw "Incorrect getAndReplace result [key=" + JSON.stringify(key0) +
-                 ", prevVal=" + prevVal.valName +
-                 ", expected=" + val0.valName + "]";
-            }
+    var f = function(args) {
+        var cache = ignite.cache("mycache");
 
-            prevVal = cache.get(key0);
-
-            if (prevVal.valName !== val1.valName) {
-                throw "Incorrect getAndReplace result [key=" + JSON.stringify(key0) + "]";
-            }
-
-            cache.removeAllFromCache();
-
-            if (cache.get(key0) !== null) {
-                throw "Incorrect removeAll result";
-            }
-
-            cache.putAll(entries);
-
-            if (cache.replace(key1, val0) !== true) {
-                throw "Incorrect replace result";
-            }
+        if (cache.remove("key1") === true) {
+            throw "Incorrect remove from empty map";
+        }
 
-            prevVal = cache.get(key1);
+        var key0 = {"keyName" : "keyVal"};
+        var key1 = {"keyName" : "keyVal1"};
+        var val0 = {"valName" : 1};
+        var val1 = {"valName" : 2};
 
-            if (prevVal.valName !== val0.valName) {
-                throw "Incorrect replace [key=" + JSON.stringify(key1) + "]";
-            }
+        var entries = [new CacheEntry(key0, val0), new CacheEntry(key1, val1)];
+        var keys = [key0, key1];
 
-            cache.removeAll(keys);
+        cache.put(key0, val0);
 
-            if (cache.size() !== 0) {
-                throw "Incorrect removeAll result.";
-            }
+        if (cache.removeValue(key0, val1) === true) {
+            throw "Incorrect removeValue from empty map [key=" + JSON.stringify(key0) + "]";
         }
 
-        function onEnd(err, res) {
-            assert(err == null);
-
-            TestUtils.testDone();
+        if (cache.remove(key0) === false) {
+            throw "Incorrect remove from empty map [key=" + JSON.stringify(key0) + "]";
         }
 
-        comp.run(f, [], onEnd.bind(null));
-    }
-
-    TestUtils.startIgniteNode(computeRunScriptRemoveOperations);
-}
-
-testComputeMapReduceGetAndPut = function() {
-    function computeMapReduceGetAndPut(error, ignite) {
-        assert(error == null, "Error on start:" + error);
-
-        var map = function(nodes, arg) {
-            for (var i = 0; i < nodes.length; i++) {
-                var f = function (val) {
-                    var prev = ignite.cache("mycache").getAndPutIfAbsent(val, val);
+        cache.put(key0, val0);
 
-                    if (prev !== null) {
-                        throw "Get and put if absent does not work.";
-                    }
-
-                    return val;
-                };
-
-                emit(f, i, nodes[i]);
-            }
-        };
-
-        var reduce = function(results) {
-            var sum = 0;
-
-            for (var i = 0; i < results.length; ++i) {
-                if (results.indexOf(i) === -1) {
-                    throw "Do not find " + i;
-                }
-
-                var prev = ignite.cache("mycache").getAndPut(i, i + 1);
-
-                if (prev !== i) {
-                    throw "Incorrect previous value [key=" + i + ", val=" + prev + "]";
-                }
-
-                sum += prev;
-            }
-
-            return sum;
-        };
-
-        var callback = function(err, res) {
-            assert(err == null, "Get error on compute task [err=" + err + "]");
-            assert(res === 1);
-
-            TestUtils.testDone();
+        if (cache.replaceValue(key0, val0, val1) === true) {
+            throw "Incorrect replaceValue result [key=" + JSON.stringify(key0) + "]";
         }
 
-        ignite.compute().mapReduce(map, reduce, [], callback);
-    }
+        var prevVal = cache.getAndReplace(key0, val1);
 
-    TestUtils.startIgniteNode(computeMapReduceGetAndPut);
-}
-
-testComputeMapReduceGetAndRemoveObject = function() {
-    function computeMapReduceGetAndRemove(error, ignite) {
-        assert(error == null, "Error on start:" + error);
-
-        var map = function(nodes, entries) {
-            for (var i = 0; i < entries.length; i++) {
-                var f = function (entry) {
-                    var cache = ignite.cache("mycache");
-                    print("ENTRY =" + entry);
-
-                    print("ENTRY Key=" + entry.key);
-
-                    if (cache.putIfAbsent(entry.key, entry.value) !== true) {
-                        throw "Incorrect put if absent result."
-                    }
-
-                    if (cache.putIfAbsent(entry.key, "1") !== false) {
-                        throw "Incorrect put if absent result."
-                    }
-
-                    return cache.getAndRemove(entry.key);
-                };
-
-                emit(f, entries[i], nodes[i % nodes.length]);
-            }
-        };
-
-        var reduce = function(results) {
-            var sum = 0;
-
-            for (var i = 0; i < results.length; ++i) {
-                sum += results[i].age;
-            }
-
-            return sum;
-        };
-
-        var callback = function(err, res) {
-            assert(err == null, "Get error on compute task [err=" + err + "]");
-            assert(res === 25, "Incorrect reduce result.");
-
-            TestUtils.testDone();
+        if (prevVal.valName !== val0.valName) {
+            throw "Incorrect getAndReplace result [key=" + JSON.stringify(key0) +
+             ", prevVal=" + prevVal.valName +
+             ", expected=" + val0.valName + "]";
         }
 
+        prevVal = cache.get(key0);
 
-        entries = [];
-
-        var key1 = {"name" : "Ann"};
-        var key2 = {"name" : "Paul"};
-        var val1 = {"age" : 12, "books" : ["1", "Book"]};
-        var val2 = {"age" : 13, "books" : ["1", "Book"]};
-
-        entries.push(new CacheEntry(key1, val1));
-        entries.push(new CacheEntry(key2, val2));
-
-        ignite.compute().mapReduce(map, reduce, entries, callback);
-    }
+        if (prevVal.valName !== val1.valName) {
+            throw "Incorrect getAndReplace result [key=" + JSON.stringify(key0) + "]";
+        }
 
-    TestUtils.startIgniteNode(computeMapReduceGetAndRemove);
-}
+        cache.removeAllFromCache();
 
-function onStart(onPut, error, ignite) {
-    var cache = ignite.cache("mycache");
+        if (cache.get(key0) !== null) {
+            throw "Incorrect removeAll result";
+        }
 
-    var params = [];
+        cache.putAll(entries);
 
-    for (var i = 900; i < 1000; ++i) {
-        params.push(new CacheEntry("key" + i,  "val" + i));
-    }
+        if (cache.replace(key1, val0) !== true) {
+            throw "Incorrect replace result";
+        }
 
-    cache.putAll(params, onPut.bind(null, ignite))
-}
+        prevVal = cache.get(key1);
 
-function computeRunScript(ignite, error) {
-    assert(error == null, "Error on put:" + error);
+        if (prevVal.valName !== val0.valName) {
+            throw "Incorrect replace [key=" + JSON.stringify(key1) + "]";
+        }
 
-    var comp = ignite.compute();
+        cache.removeAll(keys);
 
-    var f = function (args) {
-        print("!!!!" + args + " " + ignite.name());
-        return args + " " + ignite.name();
+        if (cache.size() !== 0) {
+            throw "Incorrect removeAll result.";
+        }
     }
 
-    function onEnd(err, res) {
-        assert(err == null);
-        assert(res.indexOf("NodeJsComputeSelfTest") !== -1, "Incorrect result message. [mes=" + res + "].");
-        assert(res.indexOf("GridGain") !== -1, "Incorrect result message. [mes=" + res + "].");
-
-        TestUtils.testDone();
-    }
+    TestUtils.startIgniteNode().then(function(ignite) {
+        var comp = ignite.compute();
 
-    comp.run(f, "GridGain", onEnd.bind(null));
+        comp.run(f, []).then(function(res) {
+            TestUtils.testDone();
+        }).catch(function(err) {
+            assert(err === null, err);
+        })
+    }).catch(function(err) {
+        assert(err === null, err);
+    });
 }
 
-function computeExecute(error, ignite) {
-    assert(error == null, "Error on put:" + error);
-
+testComputeMapReduceGetAndPut = function() {
     var map = function(nodes, arg) {
-        var words = arg.split(" ");
+        for (var i = 0; i < nodes.length; i++) {
+            var f = function (val) {
+                var prev = ignite.cache("mycache").getAndPutIfAbsent(val, val);
 
-        for (var i = 0; i < words.length; i++) {
-            var f = function (word) {
-                print(">>> Printing " + word);
+                if (prev !== null) {
+                    throw "Get and put if absent does not work.";
+                }
 
-                return word.length;
+                return val;
             };
 
-            emit(f, words[i], nodes[i %  nodes.length]);
+            emit(f, i, nodes[i]);
         }
     };
 
@@ -445,159 +474,90 @@ function computeExecute(error, ignite) {
         var sum = 0;
 
         for (var i = 0; i < results.length; ++i) {
-            sum += results[i];
-        }
-
-        return sum;
-    };
-
-    var callback = function(err, res) {
-        assert(err == null, "Get error on compute task [err=" + err + "]");
-        assert.equal(res, 7);
-
-        TestUtils.testDone();
-    }
-
-    ignite.compute().mapReduce(map, reduce, "Hi Alice", callback);
-}
-
-function computeAllNodeExecute(error, ignite) {
-    assert(error == null, "Error on put:" + error);
-
-    var map = function(nodes, arg) {
-        for (var i = 0; i < nodes.length; i++) {
-            var f = function (node) {
-                print(">>> Printing " + node.id().toString());
-
-                return "";
-            };
-
-            emit(f, nodes[i %  nodes.length], nodes[i %  nodes.length]);
-        }
-    };
-
-    var reduce = function(results) {};
-
-    var callback = function(err, res) {
-        assert(err == null, "Get error on compute task [err=" + err + "]");
-        TestUtils.testDone();
-    }
-
-    ignite.compute().mapReduce(map, reduce, "", callback);
-}
-
-function computeCacheExecute(error, ignite) {
-    assert(error == null, "Error on put:" + error);
-
-    var map = function(nodes, args) {
-        for (var i = 0; i < 1; i++) {
-            var f = function (args1) {
-                ignite.cache("mycache").put({"1": "1"},  2);
-
-                var val = ignite.cache("mycache").get({"1": "1"});
-
-                if (val !== 2) {
-                    throw "Incorrect return val [expected=2, val=" + val + "]";
-                }
-
-                var val1 = ignite.cache("mycache").get(args1.get(0));
-
-                if (val1["age"] !== 12) {
-                    throw "Incorrect age [expected=12, val=" + val + "]";
-                }
-
-                print("BOOKS=" + val1.books);
-
-                if (val1.books.length !== 2) {
-                    throw "Incorrect books length [expected=2, val=" +
-                        val1.books.length + "]";
-                }
+            if (results.indexOf(i) === -1) {
+                throw "Do not find " + i;
+            }
 
-                if (val1.books[0] !== "1") {
-                    throw "Incorrect books value [expected=1, val=" +
-                        val1.books[0] + "]";
-                }
-                if (val1.books[1] !== "Book") {
-                    throw "Incorrect books value [expected=Book, val=" +
-                        val1.books[1] + "]";
-                }
+            var prev = ignite.cache("mycache").getAndPut(i, i + 1);
 
-                return val1;
-            };
+            if (prev !== i) {
+                throw "Incorrect previous value [key=" + i + ", val=" + prev + "]";
+            }
 
-            emit(f, args, nodes[i]);
+            sum += prev;
         }
-    };
 
-    var reduce = function(results) {
-        return {"1" : 1};
+        return sum;
     };
 
-    var callback = function(err, res) {
-        assert(err == null, "Get error on compute task [err=" + err + "]");
-
-        assert(TestUtils.compareObject({"1": 1}, res),
-            "Incorrect result [exp= {1:1}, val=" + res);
+    TestUtils.startIgniteNode().then(function(ignite) {
+        ignite.compute().mapReduce(map, reduce, []).then(function(res) {
+            assert(res === 1);
 
-        ignite.cache("mycache").size(function(err, size){
-            assert(size === 3, "Incorrect size [size=" + 3 + ", res=" + size + "]");
             TestUtils.testDone();
+        }).catch(function(err) {
+            assert(err === null, err);
         })
-    }
-
-    entries = [];
-
-    var key1 = {"name" : "Ann"};
-    var key2 = {"name" : "Paul"};
-    var val1 = {"age" : 12, "books" : ["1", "Book"]};
-    var val2 = {"age" : 13, "books" : ["1", "Book"]};
-
-    entries.push(new CacheEntry(key1, val1));
-    entries.push(new CacheEntry(key2, val2));
-
-    ignite.cache("mycache").putAll(entries, function(err) {
-        ignite.compute().mapReduce(map, reduce, [key1, val1], callback);
+    }).catch(function(err) {
+        assert(err === null, err);
     });
 }
 
-function computeCacheSizeExecute(error, ignite) {
-    assert(error == null, "Error on put:" + error);
+testComputeMapReduceGetAndRemoveObject = function() {
+    var map = function(nodes, entries) {
+        for (var i = 0; i < entries.length; i++) {
+            var f = function (entry) {
+                var cache = ignite.cache("mycache");
+                print("ENTRY =" + entry);
+
+                print("ENTRY Key=" + entry.key);
 
-    var map = function(nodes, arg) {
-        for (var i = 0; i < nodes.length; i++) {
-            var f = function (args) {
-                print("!!!!!Node id " + ignite.localNode().id());
+                if (cache.putIfAbsent(entry.key, entry.value) !== true) {
+                    throw "Incorrect put if absent result."
+                }
 
-                return ignite.cache("mycache").localSize();
+                if (cache.putIfAbsent(entry.key, "1") !== false) {
+                    throw "Incorrect put if absent result."
+                }
+
+                return cache.getAndRemove(entry.key);
             };
 
-            emit(f, [1, 2], nodes[i]);
+            emit(f, entries[i], nodes[i % nodes.length]);
         }
     };
 
     var reduce = function(results) {
         var sum = 0;
 
-        for (var i = 0; i < results.length; i++) {
-            sum += results[i];
+        for (var i = 0; i < results.length; ++i) {
+            sum += results[i].age;
         }
 
         return sum;
     };
 
-    var callback = function(err, res) {
-        assert(err == null, "Get error on compute task [err=" + err + "]");
+    TestUtils.startIgniteNode().then(function(ignite) {
+        entries = [];
+
+        var key1 = {"name" : "Ann"};
+        var key2 = {"name" : "Paul"};
+        var val1 = {"age" : 12, "books" : ["1", "Book"]};
+        var val2 = {"age" : 13, "books" : ["1", "Book"]};
+
+        entries.push(new CacheEntry(key1, val1));
+        entries.push(new CacheEntry(key2, val2));
+
+        ignite.compute().mapReduce(map, reduce, entries).then(function(res) {
+            assert(res === 25, "Incorrect reduce result.");
 
-        ignite.cache("mycache").size(function(err, size){
-            assert(size === res, "Incorrect size [size=" + size + ", res=" + res + "]");
             TestUtils.testDone();
+        }).catch(function(err) {
+            assert(err === null, err);
         })
-    }
-
-    ignite.cache("mycache").put("key", "val",
-        function(err) {
-            ignite.compute().mapReduce(map, reduce, "", callback);
-        });
+    }).catch(function(err) {
+        assert(err === null, err);
+    });
 }
 
 testComputeFuncWithErrorExecute = function() {
@@ -641,18 +601,28 @@ testComputeIncorrectMapExecute = function() {
 }
 
 function testComputeWithErrors(map) {
-    function computeErrorExecute(error, ignite) {
-        var callback = function(err, res) {
-            assert(err != null, "Do not get error on compute task.");
-
+    TestUtils.startIgniteNode().then(function(ignite) {
+        ignite.compute().mapReduce(map, function (args) {}, "Hi Alice").then(function(res) {
+            assert(false, "Do not get an error.");
+        }).catch(function(err) {
+            assert(err !== null, err);
             assert(err.indexOf("Function evaluation failed") > -1, "Incorrect error "+
                 "[expected=function evaluation failed, value=" + err + "]");
 
             TestUtils.testDone();
-        }
+        })
+    }).catch(function(err) {
+        assert(err === null, err);
+    });
+}
 
-        ignite.compute().mapReduce(map, function (args) {}, "Hi Alice", callback);
+
+function getEntries() {
+    var params = [];
+
+    for (var i = 900; i < 1000; ++i) {
+        params.push(new CacheEntry("key" + i,  "val" + i));
     }
 
-    TestUtils.startIgniteNode(computeErrorExecute);
-}
+    return params;
+}
\ No newline at end of file


[2/3] incubator-ignite git commit: #ignite-961: rewrite query-tests.

Posted by iv...@apache.org.
#ignite-961: rewrite query-tests.


Project: http://git-wip-us.apache.org/repos/asf/incubator-ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-ignite/commit/fee4ed9e
Tree: http://git-wip-us.apache.org/repos/asf/incubator-ignite/tree/fee4ed9e
Diff: http://git-wip-us.apache.org/repos/asf/incubator-ignite/diff/fee4ed9e

Branch: refs/heads/ignite-961-promise
Commit: fee4ed9ea9210da2b87c87049ccedb7ae1d397ad
Parents: 88bb97d
Author: ivasilinets <iv...@gridgain.com>
Authored: Tue Jul 14 14:19:26 2015 +0300
Committer: ivasilinets <iv...@gridgain.com>
Committed: Tue Jul 14 14:19:26 2015 +0300

----------------------------------------------------------------------
 modules/nodejs/src/main/js/cache.js             |  46 +++--
 .../ignite/internal/NodeJsSqlQuerySelfTest.java |  10 --
 modules/nodejs/src/test/js/test-query.js        | 173 +++++++------------
 3 files changed, 99 insertions(+), 130 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/fee4ed9e/modules/nodejs/src/main/js/cache.js
----------------------------------------------------------------------
diff --git a/modules/nodejs/src/main/js/cache.js b/modules/nodejs/src/main/js/cache.js
index a84b993..f1396e3 100644
--- a/modules/nodejs/src/main/js/cache.js
+++ b/modules/nodejs/src/main/js/cache.js
@@ -268,29 +268,46 @@ Cache.prototype.size = function(callback) {
  * @param {SqlQuery|SqlFieldsQuery} qry Query
  */
 Cache.prototype.query = function(qry) {
-    if (qry.returnType() == null) {
-        qry.end("No type for sql query.");
+    var cmd;
 
-        return;
-    }
+    if (qry.type() === "Sql") {
+        if (qry.returnType() == null) {
+            return new Promise(function(resolve, reject) {
+                reject("No type for sql query.");
+            });
+        }
 
-    var command = this._createQueryCommand("qryexecute", qry).addParam("type", qry.returnType()).
-        setPostData(JSON.stringify({"arg" : qry.arguments()}));
+        cmd = this._sqlQuery(qry);
+    }
+    else {
+        cmd = this._sqlFieldsQuery(qry);
+    }
 
     var server = this._server;
+    var cache = this;
 
     return new Promise(function(resolve, reject) {
-        server.runCommand(command, function(err, res){
+        server.runCommand(cmd, function(err, res){
             if(err != null) {
                 reject(err);
             }
             else {
-                resolve(new Cursor(qry, res));
+                resolve(new Cursor(qry, res, cache));
             }
         });
     });
 }
 
+Cache.prototype._sqlFieldsQuery = function(qry) {
+    return this._createQueryCommand("qryfieldsexecute", qry).
+        setPostData(JSON.stringify({"arg" : qry.arguments()}));
+}
+
+Cache.prototype._sqlQuery = function(qry) {
+    return this._createQueryCommand("qryexecute", qry).addParam("type", qry.returnType()).
+        setPostData(JSON.stringify({"arg" : qry.arguments()}));
+}
+
 Cache.prototype.__createPromise = function(cmd) {
     var server = this._server;
 
@@ -320,9 +337,10 @@ Cache.prototype._createQueryCommand = function(name, qry) {
     return command.addParam("psz", qry.pageSize());
 }
 
-Cursor = function(qry, res) {
+Cursor = function(qry, res, cache) {
     this._qry = qry;
     this._res = res;
+    this._cache = cache;
 }
 
 Cursor.prototype.next = function() {
@@ -330,10 +348,12 @@ Cursor.prototype.next = function() {
         throw "All pages are returned.";
     }
 
-    var cmd = this._createCommand("qryfetch").addParam("qryId", _res.queryId).
-        addParam("psz", _qry.pageSize());
+    var cmd = this._cache._createCommand("qryfetch").addParam("qryId", this._res.queryId).
+        addParam("psz", this._qry.pageSize());
 
-    var server = this._server;
+    var server = this._cache._server;
+    var qry = this._qry;
+    var cache = this._cache;
 
     return new Promise(function(resolve, reject) {
        server.runCommand(cmd, function(err, res) {
@@ -341,7 +361,7 @@ Cursor.prototype.next = function() {
                reject(err);
            }
            else {
-               resolve(new Cursor(qry, res));
+               resolve(new Cursor(qry, res, cache));
            }
        });
     });

http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/fee4ed9e/modules/nodejs/src/test/java/org/apache/ignite/internal/NodeJsSqlQuerySelfTest.java
----------------------------------------------------------------------
diff --git a/modules/nodejs/src/test/java/org/apache/ignite/internal/NodeJsSqlQuerySelfTest.java b/modules/nodejs/src/test/java/org/apache/ignite/internal/NodeJsSqlQuerySelfTest.java
index e83a32e..9024b93 100644
--- a/modules/nodejs/src/test/java/org/apache/ignite/internal/NodeJsSqlQuerySelfTest.java
+++ b/modules/nodejs/src/test/java/org/apache/ignite/internal/NodeJsSqlQuerySelfTest.java
@@ -70,16 +70,6 @@ public class NodeJsSqlQuerySelfTest extends NodeJsAbstractTest {
         runJsScript("testSqlQueryWithParams");
     }
 
-
-    /**
-     * @throws Exception If failed.
-     */
-    public void testSqlPromiseQuery() throws Exception {
-        initCache();
-
-        runJsScript("testSqlPromiseQuery");
-    }
-
     /**
      * Init cache.
      */

http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/fee4ed9e/modules/nodejs/src/test/js/test-query.js
----------------------------------------------------------------------
diff --git a/modules/nodejs/src/test/js/test-query.js b/modules/nodejs/src/test/js/test-query.js
index fd01945..cbdb643 100644
--- a/modules/nodejs/src/test/js/test-query.js
+++ b/modules/nodejs/src/test/js/test-query.js
@@ -24,131 +24,84 @@ var SqlQuery = Ignite.SqlQuery;
 var SqlFieldsQuery = Ignite.SqlFieldsQuery;
 
 testSqlQuery = function() {
-    function sqlQuery(ignite, error) {
-        assert(error == null, "error on sql query [err=" + error + "]");
+    TestUtils.startIgniteNode().then(function(ignite) {
+        ignite.cache("mycache").put("key0", "val0").then(function() {
+            var qry = new SqlQuery("select * from String");
 
-        var qry = new SqlQuery("select * from String");
+            qry.setReturnType("String");
 
-        qry.setReturnType("String");
+            var fullRes = [];
 
-        var fullRes = [];
-
-        qry.on("page", function(res) {
-            fullRes = fullRes.concat(res);
-        });
-
-        qry.on("end", function(err) {
-            assert(err === null, "Error on query [err=" + err + "].");
+            function onQuery(cursor) {
+                var page = cursor.page();
 
-            assert(fullRes.length === 1, "Result length is not correct" +
-                "[expected=1, val = " + fullRes.length + "]");
+                fullRes = fullRes.concat(page);
 
-            assert(fullRes[0]["key"] === "key0", "Result value for key is not correct "+
-                "[expected=key0, real=" + fullRes[0]["key"] + "]");
+                if (cursor.isFinished()) {
+                    assert(fullRes.length === 1, "Result length is not correct" +
+                        "[expected=1, val = " + fullRes.length + "]");
 
-            assert(fullRes[0]["value"] === "val0", "Result value for key is not correct "+
-                "[expected=val0, real=" + fullRes[0]["value"] + "]");
+                    assert(fullRes[0]["key"] === "key0", "Result value for key is not correct "+
+                        "[expected=key0, real=" + fullRes[0]["key"] + "]");
 
-            TestUtils.testDone();
-        });
+                    assert(fullRes[0]["value"] === "val0", "Result value for key is not correct "+
+                        "[expected=val0, real=" + fullRes[0]["value"] + "]");
 
-        ignite.cache("mycache").query(qry);
-    }
+                    TestUtils.testDone();
 
-    function put(error, ignite) {
-        assert(error == null, "error on put [err=" + error + "]");
+                    return;
+                }
 
-        ignite.cache("mycache").put("key0", "val0", sqlQuery.bind(null, ignite))
-    }
+                cursor.next().then(onQuery);
+            }
 
-    TestUtils.startIgniteNode(put);
+            ignite.cache("mycache").query(qry).then(onQuery);
+        }).catch(function(err) {
+            assert(err === null, err);
+        })
+    }).catch(function(err) {
+        assert(err === null, err);
+    });
 }
 
-testSqlPromiseQuery = function() {
-    function sqlQuery(ignite, error) {
-        assert(error == null, "error on sql query [err=" + error + "]");
-
-        var qry = new SqlQuery("select * from String");
-        qry.setReturnType("String");
+testSqlFieldsQuery = function() {
+    TestUtils.startIgniteNode().then(function(ignite) {
+        var qry = new SqlFieldsQuery("select concat(firstName, ' ', lastName) from Person");
 
         var fullRes = [];
 
         function onQuery(cursor) {
-            console.log("RESULT PAGE=" + cursor.page())
-           fullRes = fullRes.concat(cursor.page());
+            var page = cursor.page();
 
-            if (cursor.isFinished()) {
-                console.log("Result=" + JSON.stringify(fullRes));
+            fullRes = fullRes.concat(page);
 
-                assert(fullRes.length === 1, "Result length is not correct" +
+            if (cursor.isFinished()) {
+                assert(fullRes.length === 4, "Result length is not correct" +
                     "[expected=1, val = " + fullRes.length + "]");
 
-                assert(fullRes[0]["key"] === "key0", "Result value for key is not correct "+
-                    "[expected=key0, real=" + fullRes[0]["key"] + "]");
+                fullRes.sort();
+
+                assert(fullRes[0].indexOf("Jane Doe") > -1,
+                    "Result does not contain Jane Doe [res=" + fullRes[0] + "]");
 
-                assert(fullRes[0]["value"] === "val0", "Result value for key is not correct "+
-                    "[expected=val0, real=" + fullRes[0]["value"] + "]");
+                console.log("Result: " + JSON.stringify(fullRes));
 
                 TestUtils.testDone();
 
                 return;
             }
 
-            var nextPromise = cursor.next();
-
-            nextPromise.then(onQuery);
-
+            cursor.next().then(onQuery);
         }
 
-        ignite.cachePromise("mycache").query(qry).then(onQuery);
-    }
-
-    function put(error, ignite) {
-        assert(error == null, "error on put [err=" + error + "]");
-
-        ignite.cache("mycache").put("key0", "val0", sqlQuery.bind(null, ignite))
-    }
-
-    TestUtils.startIgniteNode(put);
-}
-
-testSqlFieldsQuery = function() {
-    function sqlFieldsQuery(error, ignite) {
-        assert(error == null, "error on sqlfields query [err=" + error + "]");
-
-        var qry = new SqlFieldsQuery("select concat(firstName, ' ', lastName) from Person");
-
-        var fullRes = [];
-
-        qry.on("page", function(res) {
-            console.log("PAGE:" + res);
-            fullRes = fullRes.concat(res);
-        });
-
-        qry.on("end", function(err) {
-            assert(err === null, "Error on query [err=" + err + "].");
-
-            assert(fullRes.length === 4, "Result length is not correct" +
-                "[expected=1, val = " + fullRes.length + "]");
-
-            fullRes.sort();
-
-            assert(fullRes[0].indexOf("Jane Doe") > -1,
-                "Result does not contain Jane Doe [res=" + fullRes[0] + "]");
-
-            TestUtils.testDone();
-        });
-
-        ignite.cache("person").query(qry);
-    }
-
-    TestUtils.startIgniteNode(sqlFieldsQuery.bind(null));
+        ignite.cache("person").query(qry).then(onQuery);
+    }).catch(function(err) {
+        assert(err === null, err);
+    });
 }
 
 testSqlQueryWithParams = function() {
-    function sqlQueryWithParams(error, ignite) {
-        assert(error == null, "error on sql query [err=" + error + "]");
-
+    TestUtils.startIgniteNode().then(function(ignite) {
         var qry = new SqlQuery("salary > ? and salary <= ?");
 
         qry.setReturnType("Person");
@@ -157,25 +110,31 @@ testSqlQueryWithParams = function() {
 
         var fullRes = [];
 
-        qry.on("page", function(res) {
-            fullRes = fullRes.concat(res);
-        });
+        function onQuery(cursor) {
+            var page = cursor.page();
+
+            fullRes = fullRes.concat(page);
+
+            if (cursor.isFinished()) {
+                assert(fullRes.length === 2, "Result length is not correct" +
+                    "[expected=1, val = " + fullRes.length + "]");
 
-        qry.on("end", function(err) {
-            assert(err === null, "Error on query [err=" + err + "].");
+                assert(((fullRes[0]["value"]["firstName"].indexOf("Jane") > -1) ||
+                    (fullRes[0]["value"]["firstName"].indexOf("John") > -1)),
+                    "Result does not contain Jane and John [res=" + fullRes[0]["value"]["firstName"] + "]");
 
-            assert(fullRes.length === 2, "Result length is not correct" +
-                "[expected=1, val = " + fullRes.length + "]");
+                console.log("Result: " + JSON.stringify(fullRes));
 
-            assert(((fullRes[0]["value"]["firstName"].indexOf("Jane") > -1) ||
-                (fullRes[0]["value"]["firstName"].indexOf("John") > -1)),
-                "Result does not contain Jane and John [res=" + fullRes[0]["value"]["firstName"] + "]");
+                TestUtils.testDone();
 
-            TestUtils.testDone();
-        });
+                return;
+            }
 
-        ignite.cache("person").query(qry);
-    }
+            cursor.next().then(onQuery);
+        }
 
-    TestUtils.startIgniteNode(sqlQueryWithParams.bind(null));
+        ignite.cache("person").query(qry).then(onQuery);
+    }).catch(function(err) {
+        assert(err === null, err);
+    });
 }
\ No newline at end of file


[3/3] incubator-ignite git commit: #ignite-961: rewrite examples.

Posted by iv...@apache.org.
#ignite-961: rewrite examples.


Project: http://git-wip-us.apache.org/repos/asf/incubator-ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-ignite/commit/341f3031
Tree: http://git-wip-us.apache.org/repos/asf/incubator-ignite/tree/341f3031
Diff: http://git-wip-us.apache.org/repos/asf/incubator-ignite/diff/341f3031

Branch: refs/heads/ignite-961-promise
Commit: 341f30310c38627bd8de338b2e52ce35049a85f9
Parents: fee4ed9
Author: ivasilinets <iv...@gridgain.com>
Authored: Tue Jul 14 14:45:53 2015 +0300
Committer: ivasilinets <iv...@gridgain.com>
Committed: Tue Jul 14 14:45:53 2015 +0300

----------------------------------------------------------------------
 examples/src/main/js/cache-api-example.js       |  58 ++++------
 .../main/js/cache-not-promise-api-example.js    |  81 --------------
 .../src/main/js/cache-promise-api-example.js    |  75 -------------
 .../src/main/js/cache-promise-query-example.js  | 108 -------------------
 examples/src/main/js/cache-query-example.js     |  65 +++++------
 .../main/js/cache-sql-fields-query-example.js   |  80 ++++++++++++--
 examples/src/main/js/compute-run-example.js     |  38 ++++---
 examples/src/main/js/map-reduce-example.js      |  23 ++--
 8 files changed, 156 insertions(+), 372 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/341f3031/examples/src/main/js/cache-api-example.js
----------------------------------------------------------------------
diff --git a/examples/src/main/js/cache-api-example.js b/examples/src/main/js/cache-api-example.js
index f708160..1d4ddda 100644
--- a/examples/src/main/js/cache-api-example.js
+++ b/examples/src/main/js/cache-api-example.js
@@ -31,69 +31,57 @@ function main() {
     var cacheName = "ApiExampleCache";
 
     /** Connect to node that started with {@code examples/config/js/example-js-cache.xml} configuration. */
-    Ignition.start(['127.0.0.1:8000..9000'], null, onConnect);
-
-    function onConnect(err, ignite) {
-        if (err !== null)
-            throw "Start remote node with config examples/config/example-ignite.xml.";
-
+    Ignition.start(['127.0.0.1:8000..9000'], null).then(function(ignite) {
         console.log(">>> Cache API example started.");
 
         // Create cache on server with cacheName.
-        ignite.getOrCreateCache(cacheName, function(err, cache) {
+        ignite.getOrCreateCache(cacheName).then(function(cache){
             atomicMapOperations(ignite, cache);
         });
-    }
+    }).catch(function(err) {
+        if (err !== null)
+            console.log("Start remote node with config examples/config/example-ignite.xml.");
+    });
 
     /**
      * Demonstrates cache operations similar to {@link ConcurrentMap} API. Note that
      * cache API is a lot richer than the JDK {@link ConcurrentMap}.
      */
-    atomicMapOperations = function(ignite, cache) {
+    function atomicMapOperations (ignite, cache) {
         console.log(">>> Cache atomic map operation examples.");
 
-        cache.removeAllFromCache(function(err) {
+        cache.removeAllFromCache().then(function(){
             // Put and return previous value.
-            cache.getAndPut(1, "1", onGetAndPut)
-        });
-
-        function onGetAndPut(err, entry) {
+            return cache.getAndPut(1, "1");
+        }).then(function(entry){
             console.log(">>> Get and put finished [result=" + entry + "]");
 
             // Put and do not return previous value.
             // Performs better when previous value is not needed.
-            cache.put(2, "2", onPut);
-        }
-
-        onPut = function(err) {
+            return cache.put(2, "2")
+        }).then(function(){
             console.log(">>> Put finished.");
 
             // Put-if-absent.
-            cache.putIfAbsent(4, "44", onPutIfAbsent);
-        }
-
-        onPutIfAbsent = function(err, res) {
+            return cache.putIfAbsent(4, "44");
+        }).then(function(res){
             console.log(">>> Put if absent finished [result=" + res + "]");
 
             // Replace.
-            cache.replaceValue(4, "55", "44", onReplaceValue);
-        }
-
-        onReplaceValue = function(err, res) {
+            return cache.replaceValue(4, "55", "44");
+        }).then(function(res) {
             console.log(">>> Replace value finished [result=" + res + "]");
 
             // Replace not correct value.
-            cache.replaceValue(4, "555", "44", onEnd);
-        }
-
-        onEnd = function(err) {
+            return cache.replaceValue(4, "555", "44");
+        }).then(function(res) {
             console.log(">>> Replace finished.");
 
-            // Destroying cache.
-            ignite.destroyCache(cacheName, function(err) {
-                console.log(">>> End of Cache API example.");
-            });
-        }
+            //Destroying cache.
+            return ignite.destroyCache(cacheName);
+        }).then(function(){
+             console.log(">>> End of Cache API example.");
+        })
     }
 }
 

http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/341f3031/examples/src/main/js/cache-not-promise-api-example.js
----------------------------------------------------------------------
diff --git a/examples/src/main/js/cache-not-promise-api-example.js b/examples/src/main/js/cache-not-promise-api-example.js
deleted file mode 100644
index 519e4d7..0000000
--- a/examples/src/main/js/cache-not-promise-api-example.js
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-var apacheIgnite = require("apache-ignite");
-var Ignition = apacheIgnite.Ignition;
-
-/**
-  * This example demonstrates some of the cache rich API capabilities.
-  * <p>
-  * Start Ignite node with {@code examples/config/example-ignite.xml} configuration before running example.
-  * <p>
-  * Alternatively you can run ExampleJsNodeStartup which will
-  * start node with {@code examples/config/example-ignite.xml} configuration.
-  */
-function main() {
-    /** Cache name. */
-    var cacheName = "ApiExampleCache";
-
-    /** Connect to node that started with {@code examples/config/js/example-js-cache.xml} configuration. */
-    Ignition.start(['127.0.0.1:8000..9000'], null, onConnect);
-
-    function onConnect(err, ignite) {
-        if (err !== null)
-            throw "Start remote node with config examples/config/example-ignite.xml.";
-
-        console.log(">>> Cache API example started.");
-
-        // Create cache on server with cacheName.
-        ignite.getOrCreateCache(cacheName, function(err, promiseCache) {
-            atomicMapOperations(ignite, promiseCache);
-        });
-    }
-
-    /**
-     * Demonstrates cache operations similar to {@link ConcurrentMap} API. Note that
-     * cache API is a lot richer than the JDK {@link ConcurrentMap}.
-     */
-    atomicMapOperations = function(ignite, cache) {
-        console.log(">>> Cache atomic map operation examples.");
-
-        cache.put(1, "1", onPut1);
-
-        function onPut1(err,res) {
-            cache.get(1, onGet1);
-        }
-
-        function onGet1(err, res) {
-            if (res === "1") {
-                return cache.put(1, "2", onEnd);
-            }
-            else {
-                return cache.put(1, "3", onEnd);
-            }
-        }
-
-        function onEnd() {
-            console.log(">>> Replace finished.");
-
-            // Destroying cache.
-            ignite.destroyCache(cacheName, function(err) {
-                console.log(">>> End of Cache API example.");
-            });
-        };
-    }
-}
-
-main();
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/341f3031/examples/src/main/js/cache-promise-api-example.js
----------------------------------------------------------------------
diff --git a/examples/src/main/js/cache-promise-api-example.js b/examples/src/main/js/cache-promise-api-example.js
deleted file mode 100644
index b73b5c1..0000000
--- a/examples/src/main/js/cache-promise-api-example.js
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-var apacheIgnite = require("apache-ignite");
-var Ignition = apacheIgnite.Ignition;
-
-/**
-  * This example demonstrates some of the cache rich API capabilities.
-  * <p>
-  * Start Ignite node with {@code examples/config/example-ignite.xml} configuration before running example.
-  * <p>
-  * Alternatively you can run ExampleJsNodeStartup which will
-  * start node with {@code examples/config/example-ignite.xml} configuration.
-  */
-function main() {
-    /** Cache name. */
-    var cacheName = "ApiExampleCache";
-
-    /** Connect to node that started with {@code examples/config/js/example-js-cache.xml} configuration. */
-    Ignition.start(['127.0.0.1:8000..9000'], null, onConnect);
-
-    function onConnect(err, ignite) {
-        if (err !== null)
-            throw "Start remote node with config examples/config/example-ignite.xml.";
-
-        console.log(">>> Cache API example started.");
-
-        // Create cache on server with cacheName.
-        ignite.getOrCreatePromiseCache(cacheName, function(err, promiseCache) {
-            atomicMapOperations(ignite, promiseCache);
-        });
-    }
-
-    /**
-     * Demonstrates cache operations similar to {@link ConcurrentMap} API. Note that
-     * cache API is a lot richer than the JDK {@link ConcurrentMap}.
-     */
-    atomicMapOperations = function(ignite, cache) {
-        console.log(">>> Cache atomic map operation examples.");
-
-        cache.put(1, "1").then(function(res) {
-            return cache.get(1);
-        }).then(function(res) {
-            if (res === "1") {
-                return cache.put(1, "2");
-            }
-            else {
-                return cache.put(1, "3");
-            }
-        }).then(function() {
-            console.log(">>> Replace finished.");
-
-            // Destroying cache.
-            ignite.destroyCache(cacheName, function(err) {
-                console.log(">>> End of Cache API example.");
-            });
-        });
-    }
-}
-
-main();
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/341f3031/examples/src/main/js/cache-promise-query-example.js
----------------------------------------------------------------------
diff --git a/examples/src/main/js/cache-promise-query-example.js b/examples/src/main/js/cache-promise-query-example.js
deleted file mode 100644
index c31b8fb..0000000
--- a/examples/src/main/js/cache-promise-query-example.js
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-var apacheIgnite = require("apache-ignite");
-
-var Ignition = apacheIgnite.Ignition;
-var SqlQuery = apacheIgnite.SqlQuery;
-var SqlFieldsQuery = apacheIgnite.SqlFieldsQuery;
-var CacheEntry = apacheIgnite.CacheEntry;
-
-
-/**
-  * Cache queries example. This example demonstrates SQL queries over cache.
-  * <p>
-  * Start Ignite node with {@code examples/config/example-ignite.xml} configuration before running example.
-  * <p>
-  * Alternatively you can run ExampleJsNodeStartup which will
-  * start node with {@code examples/config/example-ignite.xml} configuration.
-  */
-main = function() {
-    /** Cache name. */
-    var cacheName = "CacheQueryExample";
-
-    /** Connect to node that started with {@code examples/config/js/example-js-cache.xml} configuration. */
-    Ignition.start(['127.0.0.1:8000..9000'], null, onConnect);
-
-    function onConnect(err, ignite) {
-        if (err !== null)
-            throw "Start remote node with config examples/config/example-ignite.xml.";
-
-        console.log(">>> Cache query example started.");
-
-        var entries = initializeEntries();
-
-        ignite.getOrCreatePromiseCache(cacheName, function(err, cache) {
-            cacheQuery(ignite, cache, entries);
-        });
-    }
-
-    function cacheQuery(ignite, cache, entries) {
-        cache.putAll(entries, onCachePut);
-
-        function onCachePut(err) {
-            console.log(">>> Create cache for people.")
-
-            //SQL clause which selects salaries based on range.
-            var qry = new SqlQuery("salary > ? and salary <= ?");
-            qry.setReturnType("Object");
-
-            // Set page size for query.
-            qry.setPageSize(2);
-
-            //Set salary range.
-            qry.setArguments([0, 2000]);
-
-            var fullRes = [];
-
-            ignite.cache(cacheName).query(qry).then(onQuery);
-
-            function onQuery(cursor) {
-                fullRes.concat(cursor.page());
-
-                if (cursor.isFinished()) {
-                    console.log("Result=" + fullRes);
-
-                    return;
-                }
-
-            	var nextPromise = cursor.next();
-
-            	nextPromise.then(onQuery);
-            }
-        }
-    }
-
-    // Initialize cache for people.
-    function initializeEntries() {
-        var key1 = "1";
-        var value1 = {"firstName" : "John", "lastName" : "Doe", "salary" : 2000};
-        var key2 = "2";
-        var value2 = {"firstName" : "Jane", "lastName" : "Doe", "salary" : 1000};
-        var key3 = "3";
-        var value3 = {"firstName" : "John", "lastName" : "Smith", "salary" : 1000};
-        var key4 = "4";
-        var value4 = {"firstName" : "Jane", "lastName" : "Smith", "salary" : 2000};
-        var key5 = "5";
-        var value5 = {"firstName" : "Ann", "lastName" : "Smith", "salary" : 3000};
-
-        return [new CacheEntry(key1, value1), new CacheEntry(key2, value2),
-            new CacheEntry(key3, value3), new CacheEntry(key4, value4)];
-    }
-}
-
-main();
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/341f3031/examples/src/main/js/cache-query-example.js
----------------------------------------------------------------------
diff --git a/examples/src/main/js/cache-query-example.js b/examples/src/main/js/cache-query-example.js
index 1c6b980..a83b577 100644
--- a/examples/src/main/js/cache-query-example.js
+++ b/examples/src/main/js/cache-query-example.js
@@ -36,26 +36,25 @@ main = function() {
     var cacheName = "CacheQueryExample";
 
     /** Connect to node that started with {@code examples/config/js/example-js-cache.xml} configuration. */
-    Ignition.start(['127.0.0.1:8000..9000'], null, onConnect);
-
-    function onConnect(err, ignite) {
-        if (err !== null)
-            throw "Start remote node with config examples/config/example-ignite.xml.";
-
+    Ignition.start(['127.0.0.1:8000..9000'], null).then(function(ignite) {
         console.log(">>> Cache query example started.");
 
-        var entries = initializeEntries();
-
-        ignite.getOrCreateCache(cacheName, function(err, cache) {
-            cacheQuery(ignite, cache, entries);
+        // Create cache on server with cacheName.
+        ignite.getOrCreateCache(cacheName).then(function(cache){
+            cacheQuery(ignite, cache);
         });
-    }
+    }).catch(function(err) {
+        if (err !== null)
+            console.log("Start remote node with config examples/config/example-ignite.xml.");
+    });
 
-    function cacheQuery(ignite, cache, entries) {
-        cache.putAll(entries, onCachePut);
+    // Run query example.
+    function cacheQuery(ignite, cache) {
+        var entries = initializeEntries();
 
-        function onCachePut(err) {
-            console.log(">>> Create cache for people.")
+        // Initialize cache.
+        cache.putAll(entries).then(function(){
+            console.log(">>> Create cache for people.");
 
             //SQL clause which selects salaries based on range.
             var qry = new SqlQuery("salary > ? and salary <= ?");
@@ -69,27 +68,31 @@ main = function() {
 
             var fullRes = [];
 
-            //This function is called when we get part of query result.
-            qry.on("page", function(res) {
+            function onQuery(cursor) {
                 console.log(">>> Get result on page: " + JSON.stringify(res));
 
-                fullRes = fullRes.concat(res);
-            });
+                //Concat query page results.
+                fullRes.concat(cursor.page());
+
+                // IsFinished return true if it is the last page.
+                if (cursor.isFinished()) {
+                    console.log(">>> People with salaries between 0 and 2000 (queried with SQL query): " +
+                        JSON.stringify(fullRes));
 
-            //This function is called when query is finished.
-            qry.on("end", function(err) {
-                console.log(">>> People with salaries between 0 and 2000 (queried with SQL query): " +
-                    JSON.stringify(fullRes));
+                    return ignite.destroyCache(cacheName);
+                }
 
-                // Destroying cache.
-                ignite.destroyCache(cacheName, function(err) {
-                    console.log(">>> End of query example.");
-                });
-            });
+                //Get Promise for next page.
+            	var nextPromise = cursor.next();
 
-            //Run query.
-            ignite.cache(cacheName).query(qry);
-        }
+            	nextPromise.then(onQuery);
+            }
+
+            // Run query.
+            ignite.cache(cacheName).query(qry).then(onQuery);
+        }).then(function(){
+            console.log(">>> End of sql query example.");
+        });
     }
 
     // Initialize cache for people.

http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/341f3031/examples/src/main/js/cache-sql-fields-query-example.js
----------------------------------------------------------------------
diff --git a/examples/src/main/js/cache-sql-fields-query-example.js b/examples/src/main/js/cache-sql-fields-query-example.js
index 58eb26b..fed91e4 100644
--- a/examples/src/main/js/cache-sql-fields-query-example.js
+++ b/examples/src/main/js/cache-sql-fields-query-example.js
@@ -22,6 +22,7 @@ var SqlQuery = apacheIgnite.SqlQuery;
 var SqlFieldsQuery = apacheIgnite.SqlFieldsQuery;
 var CacheEntry = apacheIgnite.CacheEntry;
 
+
 /**
   * Cache queries example. This example demonstrates SQL queries over cache.
   * <p>
@@ -32,24 +33,87 @@ var CacheEntry = apacheIgnite.CacheEntry;
   */
 main = function() {
     /** Cache name. */
-    var cacheName = "CacheSqlFieldsQueryExample";
+    var cacheName = "CacheQueryExample";
 
     /** Connect to node that started with {@code examples/config/js/example-js-cache.xml} configuration. */
-    Ignition.start(['127.0.0.1:8000..9000'], null, onConnect);
+    Ignition.start(['127.0.0.1:8000..9000'], null).then(function(ignite) {
+        console.log(">>> Cache sql fields query example started.");
 
-    function onConnect(err, ignite) {
+        // Create cache on server with cacheName.
+        ignite.getOrCreateCache(cacheName).then(function(cache){
+            cacheSqlFieldsQuery(ignite, cache);
+        });
+    }).catch(function(err) {
         if (err !== null)
-            throw "Start remote node with config examples/config/example-ignite.xml.";
-
-        console.log(">>> Cache sql fields query example started.");
+            console.log("Start remote node with config examples/config/example-ignite.xml.");
+    });
 
+    // Run query example.
+    function cacheSqlFieldsQuery(ignite, cache) {
         var entries = initializeEntries();
 
-        ignite.getOrCreateCache(cacheName, function(err, cache) {
-            cacheSqlFieldsQuery(ignite, cache, entries);
+        // Initialize cache.
+        cache.putAll(entries).then(function(){
+            console.log(">>> Create cache for people.");
+
+            //Sql query to get names of all employees.
+            var qry = new SqlFieldsQuery("select concat(firstName, ' ', lastName) from Person");
+
+            // Set page size for query.
+            qry.setPageSize(2);
+
+            //Set salary range.
+            qry.setArguments([0, 2000]);
+
+            var fullRes = [];
+
+            function onQuery(cursor) {
+                console.log(">>> Get result on page: " + JSON.stringify(res));
+
+                //Concat query page results.
+                fullRes.concat(cursor.page());
+
+                // IsFinished return true if it is the last page.
+                if (cursor.isFinished()) {
+                    console.log(">>> Names of all employees: " + JSON.stringify(fullRes));
+
+                    return ignite.destroyCache(cacheName);
+                }
+
+                //Get Promise for next page.
+            	var nextPromise = cursor.next();
+
+            	nextPromise.then(onQuery);
+            }
+
+            // Run query.
+            ignite.cache(cacheName).query(qry).then(onQuery);
+        }).then(function(){
+            console.log(">>> End of sql fields query example.");
         });
     }
 
+    // Initialize cache for people.
+    function initializeEntries() {
+        var key1 = "1";
+        var value1 = {"firstName" : "John", "lastName" : "Doe", "salary" : 2000};
+        var key2 = "2";
+        var value2 = {"firstName" : "Jane", "lastName" : "Doe", "salary" : 1000};
+        var key3 = "3";
+        var value3 = {"firstName" : "John", "lastName" : "Smith", "salary" : 1000};
+        var key4 = "4";
+        var value4 = {"firstName" : "Jane", "lastName" : "Smith", "salary" : 2000};
+        var key5 = "5";
+        var value5 = {"firstName" : "Ann", "lastName" : "Smith", "salary" : 3000};
+
+        return [new CacheEntry(key1, value1), new CacheEntry(key2, value2),
+            new CacheEntry(key3, value3), new CacheEntry(key4, value4)];
+    }
+}
+
+main();
+
+
     function cacheSqlFieldsQuery(ignite, cache, entries) {
         cache.putAll(entries, onCachePut.bind(null, ignite));
 

http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/341f3031/examples/src/main/js/compute-run-example.js
----------------------------------------------------------------------
diff --git a/examples/src/main/js/compute-run-example.js b/examples/src/main/js/compute-run-example.js
index 189c63f..9d2a9ad 100644
--- a/examples/src/main/js/compute-run-example.js
+++ b/examples/src/main/js/compute-run-example.js
@@ -31,25 +31,24 @@ function main() {
     var cacheName = "RunCacheScriptCache";
 
     /** Connect to node that started with {@code examples/config/js/example-js-cache.xml} configuration. */
-    Ignition.start(['127.0.0.1:8000..9000'], null, onConnect);
-
-    function onConnect(err, ignite) {
-        if (err !== null)
-            throw "Start remote node with config examples/config/example-ignite.xml.";
-
+    Ignition.start(['127.0.0.1:8000..9000'], null).then(function(ignite) {
         console.log(">>> Run cache script example started.");
 
-        ignite.getOrCreateCache(cacheName, function(err, cache) { runCacheScript(ignite, cache); });
-    }
+        // Create cache on server with cacheName.
+        ignite.getOrCreateCache(cacheName).then(function(cache){
+            runCacheScript(ignite, cache);
+        });
+    }).catch(function(err) {
+        if (err !== null)
+            console.log("Start remote node with config examples/config/example-ignite.xml.");
+    });
 
     function runCacheScript(ignite, cache) {
         var key = "John";
         var person = {"firstName": "John", "lastName": "Doe", "salary" : 2000};
 
         // Store person in the cache
-        cache.put(key, person, onPut);
-
-        function onPut(err) {
+        cache.put(key, person).then(function(){
             var job = function (args) {
                 print(">>> Hello node: " + ignite.name());
 
@@ -65,16 +64,15 @@ function main() {
                 return val.salary;
             }
 
-            var onRun = function(err, salary) {
-               console.log(">>> " + key + "'s salary is " + salary);
-
-               // Destroying cache.
-               ignite.destroyCache(cacheName, function(err) { console.log(">>> End of run cache script example."); });
-            }
-
             /** Run remote job on server ignite node with arguments [cacheName, key]. */
-            ignite.compute().run(job, [cacheName, key], onRun);
-        }
+            return ignite.compute().run(job, [cacheName, key]);
+        }).then(function(salary){
+            console.log(">>> " + key + "'s salary is " + salary);
+
+            return ignite.destroyCache(cacheName);
+        }).then(function() {
+            console.log(">>> End of run cache script example.");
+        });
     }
 }
 

http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/341f3031/examples/src/main/js/map-reduce-example.js
----------------------------------------------------------------------
diff --git a/examples/src/main/js/map-reduce-example.js b/examples/src/main/js/map-reduce-example.js
index db2da87..93913fe 100644
--- a/examples/src/main/js/map-reduce-example.js
+++ b/examples/src/main/js/map-reduce-example.js
@@ -32,12 +32,7 @@ var Ignition = apacheIgnite.Ignition;
   */
 function main() {
     /** Connect to node that started with {@code examples/config/js/example-js-cache.xml} configuration. */
-    Ignition.start(['127.0.0.1:8000..9000'], null, onConnect);
-
-    function onConnect(err, ignite) {
-        if (err !== null)
-            throw "Start remote node with config examples/config/example-ignite.xml.";
-
+    Ignition.start(['127.0.0.1:8000..9000'], null).then(function(ignite) {
         console.log(">>> Compute map reduce example started.");
 
         /**
@@ -72,14 +67,14 @@ function main() {
             return sum;
         }
 
-        // Called when map reduced finished.
-        var onMapReduce = function(err, cnt) {
-            console.log(">>> Total number of characters in the phrase is '" + cnt + "'.");
-            console.log(">>> End of compute map reduce example.");
-        }
-
-        ignite.compute().mapReduce(map, reduce, "Hello Ignite Enabled World!", onMapReduce);
-    }
+        return ignite.compute().mapReduce(map, reduce, "Hello Ignite World!");
+    }).then(function(cnt){
+        console.log(">>> Total number of characters in the phrase is '" + cnt + "'.");
+         console.log(">>> End of compute map reduce example.");
+    }).catch(function(err) {
+        if (err !== null)
+            console.log("Start remote node with config examples/config/example-ignite.xml. ");
+    });
 }
 
 main();
\ No newline at end of file