简体   繁体   English

是否有可能简化承诺中的承诺解决?

[英]Is it possible to simplify promise resolve inside a promise?

I've found a way to asynchronously load modules, but the result looks somewhat scary. 我找到了一种异步加载模块的方法,但结果看起来有些可怕。

export default Promise.all([
    // asynchronously load modules:
    System.import('./details.js'),
    System.import('./chartHelper.js'),
    System.import('./dateHelper.js')
]).then(promises => {
    // modules returned promises, so resolve them:
    Promise.all([
        promises[0].default,
        promises[1].default,
        promises[2].default
    ]).then(modules => {
        // assign modules to variables:
        var details = modules[0];
        var chartHelper = modules[1];
        var dateHelper = modules[2];

        /* ...code dependent on loaded modules... */
    });
});

Is there a way I can simplify this? 有没有办法可以简化这个?

For instance, is there a synctatic sugar to resolve a result of the promise if the response of the original promise is also a promise? 例如,如果原始承诺的回应也是一个承诺,是否有一个分析糖来解决承诺的结果? Or can I at least use named properties instead array indexes here? 或者我至少可以在这里使用命名属性而不是数组索引?

You could improve readability doing something like that: 您可以通过这样的方式提高可读性:

export default Promise
  .all(
    ['details', 'chartHelper', 'dateHelper']
      .map(m => (
        System.import(`./${m}.js`).then(m => m.default)
      ))
  )
  .then(([details, chartHelper, dateHelper]) => {

    console.log({details, chartHelper, dateHelper});
  })
;

Does this count as simpler? 这算得上更简单吗?

export default Promise.all([
    // asynchronously load modules:
    System.import('./details.js'),
    System.import('./chartHelper.js'),
    System.import('./dateHelper.js')
]).then(promises => 
    Promise.all(promises.map(promise => promise.default))
).then([details, chartHelper, dateHelper] => {
    /* ...code dependent on loaded modules... */
});

(Incidentally, you had a slight bug: you weren't actually returning the value from the second Promise.all() .) (顺便说一下,你有一个小错误:你实际上没有从第二个Promise.all()返回值。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM