确保执行顺序:javascript

Ensuring order of execution : javascript

我试图在单击按钮时加载 google 地图 JS(而不是包含在 Head 中以进行优化)。

     $.when(
           $.getScript("https://maps.googleapis.com/maps/api/js?v=3.17&libraries=places")
               .done(function() {
                 console.log('loaded');
               })
        )
        .then(_getCurrentLocation())
        .then(_lookForLatLang())  

getCurrentLocation 只不过是浏览器支持的基于反向查找的地理定位对象。

我想严格遵循 Javascript 个文件的执行顺序,但效果并不理想。我可以先看到 getCurrentLocation 的输出,然后是 getScript 日志。

脚本有什么问题?

.then(_getCurrentLocation())

您刚刚调用 _getCurrentLocation 立即 并将返回值传递给 then() (就像任何其他函数调用一样)。

您想传递函数本身。

使用回调:

$.getScript("https://maps.googleapis.com/maps/api/js?v=3.17&libraries=places")
    .done(function() {
        console.log('loaded');
    }, function () {
        _getCurrentLocation();
        _lookForLatLang();
    });

$.getScript("https://maps.googleapis.com/maps/api/js?v=3.17&libraries=places")
  .done(function() {
    console.log('loaded');
    _getCurrentLocation();
    _lookForLatLang();
  });