在JS对象中异步加载数据

时间:2013-03-16 10:14:36

标签: javascript ajax json dojo

我正在为我的网上商店应用程序编写一个JS类来访问存储在服务器上的产品信息。应该异步加载信息。为此我使用dojo.xhrPost()。我想重写一个名为getProductName(productId:int):String的类的函数,它返回给定产品ID的产品名称。该函数使用实习生dojo.xhrPost()。但是我应该返回加载的产品名称,因为我必须将新函数传递给dojo.xhrPost()中的加载和错误?

使用此功能:其他JS函数调用此方法加载产品名称以更新购物车网页而无需重新加载整个页面。返回的数据采用JSON格式,因为传输了一些附加信息以进行错误处理(客户端函数必须知道服务器端是否发生了任何错误)。

函数getProductName(productId:int)的代码:

      function getProductName(productId) {
         dojo.xhrPost({
            url: '/shop/dataProduct.php',
            handleAs: 'json',
            content: {productId:productId},
            load: function(response, ioArgs) {
                 if (!response.error) {
                    // here I would like to return response.data to the caller of myObj.getProductName(productId)
                 } else {
                    // here I would like to return "error" to the caller of myObj.getProductName(productId)
                 }
                 return response;
            },
            error: function(response, ioArgs) {
                // here I would like to return "error" to the caller of myObj.getProductName(productId)
                return response;
            }
         });
      }

用法:

           var productName = myObj.getProductName(5);

1 个答案:

答案 0 :(得分:0)

以下代码行的问题在于它假设产品名称的检索是同步的。但是你正在进行ajax调用以获取名称,因此代码是异步的。

var productName = myObj.getProductName(5);

您需要使用dojo/Deferred来处理异步调用。

function getProductName(productId) {

     var d = new dojo.Deferred();

     dojo.xhrPost({
        url: '/shop/dataProduct.php',
        handleAs: 'json',
        content: {productId:productId},
        load: function(response, ioArgs) {
             if (!response.error) {
                var productName = ???;
                d.resolve(productName);
             } else {
                d.reject(response.error);
             }
        },
        error: function(err) {
            d.reject(err);
        }
     });

     return d;
}

用法:

getProductName(1).then(
  function(productName) {
     // do something with product name

  }, function(error) {
     // handle error
  });

http://dojotoolkit.org/reference-guide/1.8/dojo/Deferred.html