System.import承诺链接

问题描述 投票:3回答:3

我偶然发现了一些片段similar to this one

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

它是否代替回调地狱 - 一个承诺地狱?顺序System.imports可以扁平化以使用承诺链,或者可能存在问题吗?

javascript promise ecmascript-6 systemjs
3个回答
9
投票

我推荐链接,例如

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.
});

2
投票

在这种情况下,我更喜欢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!!!');
}
© www.soinside.com 2019 - 2024. All rights reserved.