【问题标题】:System.import promise chainingSystem.import 承诺链
【发布时间】:2015-11-08 16:49:08
【问题描述】:

我偶然发现了一些 sn-ps similar to this one:

  System.import('core-js').then( function() {
    System.import('polymer/mutationobservers').then( function() {
      System.import('aurelia-bootstrapper');
    })
  });

它是回调地狱的替代品 - 承诺地狱吗?可以将连续的System.imports 展平以使用 Promise 链接,还是可能存在问题?

【问题讨论】:

  • @torazaburo 我只是在引用现有的代码片段,但是是的,这三个模块相互依赖。前两个是 polyfill 库,如果需要,由开发人员选择。
  • @torazaburo 他链接到代码所在的位置。它明确表示,如果您想要 IE9 支持,则必须加载它们,但它们是可选的。 sn-p 直接来自 Aurelia 网站。它们确实相互依赖,因为它们是 polyfills 并且依赖于存在的全局变量。
  • @estus - 不幸的是,promise 被广泛误解,所以是的,你会经常遇到这样的代码。话虽如此,有一些合法的方法可以避免回调地狱 - 创造大量回调的人可能在创造大量承诺时没有问题。
  • @aaaaaa 在体面的框架文档中看到这一点令人困惑(我认为 Aurelia 是一个体面的文档),所以让我想知道这背后是否有某种原因。

标签: javascript promise ecmascript-6 systemjs


【解决方案1】:

我建议改为链接,例如

System.import('core-js')
    .then(function(){
        return System.import('polymer/mutationobservers');
    })
    .then(function(){
        return System.import('aurelia-bootstrapper');
    });

当你 return 来自 then 的承诺时,它会在执行下一个 then 之前等待该承诺解决,因此在这种情况下 mutationobservers 必须在 aurelia-bootstrapper 之前加载。

【讨论】:

    【解决方案2】:

    由于 System.import 返回一个 Promise,所以使用一组 Promise。我发现它比链接更直接。

    Promise.all([
        System.import('core-js'),
        System.import('polymer/mutationobservers'),
        System.import('aurelia-bootstrapper')
    ]).then(function(modules) {
        var corejs = modules.shift(),
            mutationobservers = modules.shift(),
            aureliaBootstrapper = modules.shift()
        ;
    
        // You code goes here.
    });
    

    【讨论】:

    • 我猜这里的问题是前两个是polyfill库。但除此之外,是的,这将是 Promise.all 的一个很好的用例。
    • 使用 es6 解构,可以避免使用modules.shift() 来分配模块变量,例如.then(([corejs, mutationobservers, aureliaBootstrapper]) => { // your code ...
    【解决方案3】:

    在这种情况下我更喜欢 async/await,但是你需要在一个异步函数中,这可能并不总是适用于 import 语句

    function async doStuff () {
        await System.import('core-js');
        await System.import('polymer/mutationobservers');
        await System.import('aurelia-bootstrapper');
        console.log('everything done!!!');
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-15
      • 2023-03-26
      • 2023-01-27
      相关资源
      最近更新 更多