(#3605) - fix immediate cancel of live replication

The example from the docs where the user immediately
calls `cancel()` on a live replication is actually
broken, because we don't detect it if it's canceled
in the same turn of the event loop. This fixes that.
diff --git a/lib/replicate.js b/lib/replicate.js
index c302344..de6228d 100644
--- a/lib/replicate.js
+++ b/lib/replicate.js
@@ -541,6 +541,10 @@
     });
   }
 
+  if (returnValue.cancelled) { // cancelled immediately
+    completeReplication();
+    return;
+  }
 
   returnValue.once('cancel', completeReplication);
 
diff --git a/tests/integration/test.replication.js b/tests/integration/test.replication.js
index 8c1a84d..1b9cc66 100644
--- a/tests/integration/test.replication.js
+++ b/tests/integration/test.replication.js
@@ -3375,6 +3375,22 @@
       });
     });
 
+    it('Test immediate replication canceling', function (done) {
+      //See  http://pouchdb.com/guides/replication.html : Cancelling replication
+      var db = new PouchDB(dbs.name);
+      var remote = new PouchDB(dbs.remote);
+      var replicationHandler = remote.replicate.to(db, {
+        live: true,
+        retry: true
+      });
+
+      replicationHandler.on('complete', function () {
+        done();
+      }).on('error', done);
+
+      replicationHandler.cancel();
+    });
+
     it('#3171 Unauthorized validate_doc_update error message',
         function (done) {
       testUtils.isCouchDB(function (isCouchDB) {