]> source.dussan.org Git - gwtquery.git/commitdiff
Re-write Promise.then since it must return a new promise instead of itself
authorManuel Carrasco Moñino <manuel.carrasco.m@gmail.com>
Mon, 18 Mar 2013 16:18:42 +0000 (17:18 +0100)
committerManuel Carrasco Moñino <manuel.carrasco.m@gmail.com>
Mon, 18 Mar 2013 16:18:42 +0000 (17:18 +0100)
gwtquery-core/src/main/java/com/google/gwt/query/client/Promise.java
gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/ajax/Ajax.java
gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/deferred/Callbacks.java
gwtquery-core/src/main/java/com/google/gwt/query/client/plugins/deferred/Deferred.java
gwtquery-core/src/test/java/com/google/gwt/query/client/GQueryAjaxTestGwt.java
gwtquery-core/src/test/java/com/google/gwt/query/client/GQueryDeferredTestGwt.java

index 03c7327bf3f0dda9730918e1c0ea456944b77ed4..3785b9c31eecc74cf5ec8cec6900c635bf65fb90 100644 (file)
@@ -87,8 +87,13 @@ public interface Promise {
   String state();
 
   /**
-   * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress.
-   * 
+   * Add filters to be called when the Deferred object is resolved, rejected, or still in progress.
+   *
+   * These handlers are used to eventually change the values used to resolve the promise.
+   *
+   * `then` returns a new Promise which will be resolved with the values returned by the handlers
+   * in old jquery versions `then` was called `pipe`.
+   *
    * @param f a list of 1, 2, or 3 functions, which will be used in this way:
    *   1st function will be called when the deferred is resolved.
    *   2nd function that is called when the deferred is rejected.
index fefcb67f79a036e58d4709f564c4e68f2778e458..6f094d5ed0ee44d2a2401b3d0bd576b86dac5c2e 100644 (file)
@@ -2,6 +2,7 @@ package com.google.gwt.query.client.plugins.ajax;
 
 import com.google.gwt.core.client.GWT;
 import com.google.gwt.dom.client.Element;
+import com.google.gwt.http.client.Request;
 import com.google.gwt.http.client.RequestBuilder;
 import com.google.gwt.http.client.RequestBuilder.Method;
 import com.google.gwt.http.client.Response;
@@ -13,8 +14,8 @@ import com.google.gwt.query.client.builders.JsonBuilder;
 import com.google.gwt.query.client.js.JsUtils;
 import com.google.gwt.query.client.plugins.Plugin;
 import com.google.gwt.query.client.plugins.deferred.Deferred;
-import com.google.gwt.query.client.plugins.deferred.PromiseReqBuilderJSONP;
 import com.google.gwt.query.client.plugins.deferred.PromiseReqBuilder;
+import com.google.gwt.query.client.plugins.deferred.PromiseReqBuilderJSONP;
 import com.google.gwt.user.client.ui.FormPanel;
 
 /**
@@ -110,13 +111,11 @@ public class Ajax extends GQuery {
     final Function onSuccess = settings.getSuccess();
     if (onSuccess != null) {
       onSuccess.setElement(settings.getContext());
-      dfd.promise().done(onSuccess);
     }
 
     final Function onError = settings.getError();
     if (onError != null) {
       onError.setElement(settings.getContext());
-      dfd.promise().fail(onError);
     }
 
     Method httpMethod = resolveHttpMethod(settings);
@@ -125,41 +124,39 @@ public class Ajax extends GQuery {
     final String dataType = settings.getDataType();
 
     if ("jsonp".equalsIgnoreCase(dataType)) {
-      int timeout = settings.getTimeout();
-      return getJSONP(url, onSuccess, onError, timeout);
-    }
-
-    createPromiseRequestBuilder(settings, httpMethod, url, data)
-      .done(new Function() {
-        public void f() {
-          Response response = arguments(0);
-          Response request = arguments(1);
-          Object retData = null;
-          try {
-            if ("xml".equalsIgnoreCase(dataType)) {
-              retData = JsUtils.parseXML(response.getText());
-            } else if ("json".equalsIgnoreCase(dataType)) {
-              retData = JsUtils.parseJSON(response.getText());
-            } else {
-              retData = response.getText();
-            }
-          } catch (Exception e) {
-            if (GWT.getUncaughtExceptionHandler() != null) {
-              GWT.getUncaughtExceptionHandler().onUncaughtException(e);
+      return getJSONP(url, onSuccess, onError, settings.getTimeout());
+    } else {
+      return createPromiseRequestBuilder(settings, httpMethod, url, data)
+        .then(new Function() {
+          public Object f(Object...args) {
+            Response response = (Response)args[0];
+            Request request = (Request)args[1];
+            Object retData = null;
+            try {
+              if ("xml".equalsIgnoreCase(dataType)) {
+                retData = JsUtils.parseXML(response.getText());
+              } else if ("json".equalsIgnoreCase(dataType)) {
+                retData = JsUtils.parseJSON(response.getText());
+              } else {
+                retData = response.getText();
+              }
+            } catch (Exception e) {
+              if (GWT.getUncaughtExceptionHandler() != null) {
+                GWT.getUncaughtExceptionHandler().onUncaughtException(e);
+              }
             }
+            return new Object[]{retData, "success", request, response};
           }
-          dfd.resolve(retData, "success", request, response);
-        }
-      })
-      .fail(new Function() {
-        public void f() {
-          Throwable exception = arguments(0);
-          Response request = arguments(1);
-          dfd.reject(null, exception.getMessage(), request, null, exception);
-        }
-      });
-    
-    return dfd.promise();
+        }, new Function() {
+          public Object f(Object...args) {
+            Throwable exception = (Throwable)args[0];
+            Response request = (Response)args[1];
+            return new Object[]{null, exception.getMessage(), request, null, exception};
+          }
+        })
+        .done(onSuccess)
+        .fail(onError);
+    }
   }
   
   private static Promise createPromiseRequestBuilder(Settings settings, Method httpMethod, String url, String data) {
index 5471ed29308d4208b7cb3d98014696b413ca32d2..a81c92e7f7938969f6157ce450dea57f90fa359f 100644 (file)
@@ -175,6 +175,10 @@ public class Callbacks {
 
   @SuppressWarnings({"unchecked", "rawtypes"})
   private boolean run(Object c, Object...o) {
+    // Unbox array into array, it happens when running filters in Promise.then
+    if (o.length == 1 && o[0].getClass().isArray()) {
+      o = (Object[])o[0];
+    }
     if (c instanceof Callback) {
       return ((Callback)c).f(o);
     } else if (c instanceof Function) {
index 027d230b6d9f3b2d293538d90a51c523c0eda590..b086773e55d26b7b84d3d4d4c1941b277697fb05 100644 (file)
@@ -68,14 +68,24 @@ public class Deferred extends GQuery implements Promise.Deferred {
       return dfd.state;
     }
     
-    public Promise then(Function... f) {
-      assert f.length < 4 : "Promise.then: Too much arguments";
-      switch (f.length) {
-        case 3: progress(f[2]);
-        case 2: fail(f[1]);
-        case 1: done(f[0]);
-      }
-      return this;
+    public Promise then(final Function... f) {
+      final Deferred newDfd = new com.google.gwt.query.client.plugins.deferred.Deferred();
+      progress(new Function() {
+        public void f() {
+          newDfd.notify(f.length > 2 ? f[2].f(getArguments()) : getArguments());
+        }
+      });
+      fail(new Function() {
+        public void f() {
+          newDfd.reject(f.length > 1 ? f[1].f(getArguments()) : getArguments());
+        }
+      });
+      done(new Function() {
+        public void f() {
+          newDfd.resolve(f.length > 0 ? f[0].f(getArguments()) : getArguments());
+        }
+      });
+      return newDfd.promise();
     }
 
     public boolean isResolved() {
index c257971b6cc12d64e4e1abfe288a7798d133b6a0..292d74c6f074c97c30693ae7af9ed718e15294d1 100644 (file)
@@ -271,7 +271,7 @@ public class GQueryAjaxTestGwt extends GWTTestCase {
     }, 500);
   }
 
-  public void testJsonTimeout() {
+  public void testJsonpTimeout() {
     delayTestFinish(5000);
     String nonJsonpUrl = "http://127.0.0.1/nopage";
 
@@ -292,5 +292,26 @@ public class GQueryAjaxTestGwt extends GWTTestCase {
 
     Ajax.ajax(s);
   }
+  
+  public void testAjaxError() {
+    delayTestFinish(5000);
+    String url = "http://127.0.0.1/nopage";
+    
+    Ajax.ajax(Ajax.createSettings().setTimeout(1000).setUrl(url))
+      .done(new Function(){
+        public void f() {
+          fail();
+        }
+      }).fail(new Function(){
+        public void f() {
+          System.out.println(arguments(0));
+          System.out.println(arguments(1));
+          System.out.println(arguments(2));
+          System.out.println(arguments(3));
+          System.out.println(arguments(4));
+          finishTest();
+        }
+      });
+  }
 
 }
index 8c011a247e8ed6c447bba2cb9b730d7c698658df..d5cbcb77ec1795b1d7c7540d45a4ccc5ed106915 100644 (file)
@@ -19,8 +19,8 @@ package com.google.gwt.query.client;
 import com.google.gwt.junit.client.GWTTestCase;
 import com.google.gwt.query.client.plugins.ajax.Ajax;
 import com.google.gwt.query.client.plugins.deferred.Callbacks;
-import com.google.gwt.query.client.plugins.deferred.PromiseFunction;
 import com.google.gwt.query.client.plugins.deferred.Callbacks.Callback;
+import com.google.gwt.query.client.plugins.deferred.PromiseFunction;
 import com.google.gwt.user.client.Timer;
 
 /**
@@ -258,4 +258,24 @@ public class GQueryDeferredTestGwt extends GWTTestCase {
         });
       }
 
+      public void testWhen() {
+        new PromiseFunction() {
+          public void f(final Deferred dfd) {
+            dfd.resolve(5);
+          }
+        }.done(new Function() {
+          public void f() {
+            assertEquals(5d, arguments(0));
+          }
+        }).then(new Function() {
+          public Object f(Object... args) {
+            return (Double)args[0] * 2;
+          }
+        }).done(new Function() {
+          public void f() {
+            assertEquals(10d, arguments(0));
+          }
+        });
+      }
+
 }