2017-05-12 32 views
0

我見過他們使用以下語法嵌套回調某些API文檔中:這是在Javascript中縮進嵌套回調的推薦方式嗎?

webmap = new WebMap({ 
    portalItem: { 
    id: "id" 
    } 
}) 
    .load() 
     .then(function(instance){ 
      console.log(instance); 
      view = new MapView({ 
       map: instance, 
       container: "map" 
      }) 
       .then(function(instance){ 

       }) 
      ; 
     }) 
    ; 
; 

這是推薦的方式,語法在Javascript中嵌套調用?

另外,爲什麼?作爲來自Python的人,這似乎很奇怪,也沒有必要。

如果有人好奇,我見過identation這種方式主要是在語義UI的例子https://semantic-ui.com/modules/sidebar.html#/examples

+4

我建議你使用風格指南,因爲代碼格式是一個主觀的話題,不能有堆棧溢出的規範答案。人們會根據他們的意見而不是回答質量進行投票。 FWIW我從來沒有見過任何人格式化他們的代碼。 – 4castle

回答

3

當你深深嵌套then電話,你可能要檢查,如果這是真的有必要。在你的情況下,它不是。移動內部then調用外鏈:

webmap = new WebMap({ 
    portalItem: { 
     id: "id" 
    } 
}).load().then(function(instance){ 
    console.log(instance); 
    // return (!) the promise, instead of applying a nested `then` 
    return new MapView({ 
     map: instance, 
     container: "map" 
    }); 
}).then(function(instance){ // the `then` is now on the outer chain. 

}); 

這樣壓痕深度保持合理的,這是承諾的優點(當你用好)之一。

+0

是的。嵌套函數調用是.then()調用的目的是防止。 –

+0

啊我看到了,看起來更有希望 – Mojimi

+0

關於從'MapView'返回內部承諾然後在外部'then'處理內部承諾的好處。 – Dai

1

您使用的是Promise接口(或類似於它的東西),這樣你就不會實際使用傳統意義上的嵌套回調 - 雖然我看到您的.then()MapView建設將算作一個。

then調用了同樣的事件順序應該是在同一縮進級別,事件嵌套序列應該還是有它的所有事件在同一水平。這是我會怎麼格式化:

webmap = new WebMap({ 
     portalItem: { 
      id: "id" 
     } 
    }) 
    .load() 
    .then(function(instance) { 
     console.log(instance); 
     view = new MapView({ 
      map: instance, 
      container: "map" 
     }) 
     .then(function(instance) { 

     }); 
    }); 

注意可以讓這個更簡潔的用箭頭功能語法:

webmap = new WebMap({ 
     portalItem: { 
      id: "id" 
     } 
    }) 
    .load() 
    .then(instance => { 
     console.log(instance); 
     view = new MapView({ 
      map: instance, 
      container: "map" 
     }) 
     .then(instance => { 

     }); 
    }); 

,如果您將匿名options的物品運到可讀性可以改進事件的順序,但由於MapView構造函數的options取值instance在這種情況下不是一個選項。

但對於WebMap構造,您可以:

var webMapOption = { portalItem: { id: "id" } }; 
webMap = new WebMap(webMapOptions) 
    .load() 
    .then(instance => ...); 
+0

第4行缺少'}',所以現在我很困惑,因爲如果你能解決這個問題 – Mojimi

+0

@Mojimi謝謝。我修復了它。 – Dai

+0

@Mojimi,我認爲重新做​​出這個決定是正確的答案是明智的。上面的代碼沒有按照任何標準慣例進行格式化(而且看起來很差勁的IMO)。看看標準JS如何完成 - https://standardjs.com/rules.html - 感受一下。 –

相關問題