2017-04-18 88 views
1

这可能是一个愚蠢的问题,但我总是问,我有一个关于等待回调的问题。等待在javascript中加载元素

我在我的网站开发项目中使用聚合物。在我的网页之一,我有一个循环加载一个循环内的元素:从“元素,一个”从数据库查询结果填充数据库和内容

loop 
    "element-a" 
end loop 

我获取数据。 我只想在“element-a”加载完成后加载另一个“element-a”。

现在,我有一个强制延迟使用: sleepStupidly(usec); function sleepStupidly(usec) var endtime = new Date()。getTime()+ usec; (新日期().getTime()< endtime); }

但我需要一个更好的方式来做到这一点,任何建议都会有所帮助。

+0

而不是“sleepStupidly”,你可以简单地使用window.setTimeout。但是这并不能解决你的基本问题,那就是你的数据是异步获取的,所以你不知道它到底什么时候可用。请张贴获取数据的代码。 –

+1

我不使用聚合物,但这听起来像是一个JavaScript承诺的工作 - 或ajax成功。 – sheriffderek

+0

https://developers.google.com/web/fundamentals/getting-started/primers/promises#promisifying_xmlhttprequest – sheriffderek

回答

0

由于sheriffderek在评论中指出,承诺或jQuery的$ .ajax()。success()方法可能是完成这项工作的最佳工具。另外,还可以使用良好的ol递归。以下是如何在Polymer(v1)组件中针对您的情况使用这些组件的示例。

<dom-module id="example-component"> 
    <template></template> 
    <script> 
     Polymer({ 
      is:"example-component", 
      properties: { 
       //... 
      }, 
      fetchIndex: 0, 
      idsToFetch: [1, 2, 3, 4], 
      elementData: [], 
      ready: function() { 
       this.loadElement(this.idsToFetch[this.fetchIndex]); 
      }, 
      loadElement: function(idToFetch) { 
       var self = this;  // Create a reference for the ".done()" method to use when it fires 
       $.ajax({ 
        url: "http://example.com/getdata", 
        data: {"idToFetch": idToFetch} 
       }).done(function (data) {   // This will fire after the response is received, which is where you call the next 
        self.elementData.push(data); // Save the response data 
        self.fetchIndex++;          // Move to the next element 
        if (self.fetchIndex < self.idsToFetch.length) {   // If there's more to fetch 
         self.loadElement(self.idsToFetch[self.fetchIndex]); // Recursively call the same method 
        } 
       }).always(function(data){         // Optional 
        console.log("Fetch complete for ID: " + idToFetch); 
       }).error(function (error){         // Optional 
        console.log(error) 
       }); 
      } 
     }) 
    </script> 
</dom-module> 

综上所述,呼吁聚合物的ready()处理程序loadElement()方法,并提供其发起获取的第一要素。在loadElement()之内,使获取获取传入的元素ID的数据。一旦获取是.done()(首选,但类似于.success()),则递归地再次调用loadElement()方法,并将其提供给列表中的下一个元素。这将继续递归直到fetchIndex值等于idsToFetch阵列的长度。