这是在 Javascript 中缩进嵌套回调的推荐方法吗?

Is this the recommended way to indent nested callbacks in Javascript?

我在一些 API 文档中看到它们使用以下语法进行嵌套回调:

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出身的人来说,显得很奇怪也没有必要

如果有人好奇,我主要在语义 Ui 的示例中看到这种识别方式 https://semantic-ui.com/modules/sidebar.html#/examples

您使用的是 Promise 接口(或类似的东西),因此您实际上并没有使用传统意义上的嵌套回调 - 虽然我在 [= 之后看到了您的 .then() 15=] 建筑算作一个。

对同一事件序列的 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 => ... );

当您有深度嵌套的 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.

});

这样缩进的深度保持合理,这是promise的优点之一(当你用好它们的时候)。