我偶然发现了一些片段similar to this one:
System.import('core-js').then( function() {
System.import('polymer/mutationobservers').then( function() {
System.import('aurelia-bootstrapper');
})
});
它是否代替回调地狱 - 一个承诺地狱?顺序System.import
s可以扁平化以使用承诺链,或者可能存在问题吗?
我推荐链接,例如
System.import('core-js')
.then(function(){
return System.import('polymer/mutationobservers');
})
.then(function(){
return System.import('aurelia-bootstrapper');
});
当你return
来自then
的承诺时,它会在执行下一个then
之前等待解决,所以在这种情况下mutationobservers
必须在aurelia-bootstrapper
之前加载。
由于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.
});
在这种情况下,我更喜欢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!!!');
}