【问题标题】:Javascript, Ember 2, How to refactor this code of promises (maybe also with async/await)Javascript,Ember 2,如何重构这个 Promise 代码(也可以使用 async/await)
【发布时间】:2017-09-08 21:48:15
【问题描述】:

如何重构下面的代码?

get(category, "posts").then(posts => {
  return all(
    posts.map(post =>
      get(post, "words").then(words => {
        return all(
          words.map(word => {
            if (!get(word, "hasDirtyAttributes")) {
              return false;
            }
            return word
              .save()
              .then(() => this.ok())
              .catch(error => this.error(error));
          })
        );
      })
    )
  );
});

另外,我想了解当我对此代码有以下 lint 规则时如何避免使用许多函数:

[eslint] Use named functions defined on objects to handle promises (ember/named-functions-in-promises)

如何使用异步/等待?

【问题讨论】:

  • 这个函数的响应怎么用?你甚至需要它吗? this.ok()this.error() 是什么?
  • 两个这样的小函数:console.log(error)。无论如何,问题是这段代码。你会怎么做?
  • get() 有点混乱。在第一次和第二次使用时,它似乎是异步,而在第三次使用时,它似乎是同步。是哪个?
  • 最好和最简单的改进似乎是扁平化代码,给出一个包含get().then(posts => ...).then(words => ...).catch(error => ...) 的主链,它更干净,.catch() 将比其当前的嵌套范围更全面。 .then(() => this.ok()) 表达式应保持嵌套。
  • 重构的目标是什么?您可以通过多种方式“重构”该代码,您必须了解为什么要“重构”

标签: javascript ember.js promise async-await refactoring


【解决方案1】:

我认为您可以减少的最复杂的方法是展平数组。但是,如果您需要该代码的结果,这将不起作用。但是我假设您只想保存所有单词。

然后我会做这样的事情:

get(category, "posts").then(posts => {
  return all(posts.map(post => get(post, "words")));
})
.then(wordOfWords => wordOfWords.reduce((a, b) => [...a, ...b], []))
.then(words => all(words.map(word => get(word, "hasDirtyAttributes") && word.save()))});

或使用异步函数:

const posts = await get(category, "posts");
const wordOfWords = await all(posts.map(post => get(post, "words")));
const words = wordOfWords.reduce((a, b) => [...a, ...b], []);
const wordsWithDirtyAttrs = words.filter(word => get(word, "hasDirtyAttributes"));
await all(wordsWithDirtyAttrs.map(word => word.save()));

但是,如果您真的需要这种结构,我会将您的代码拆分为多个函数。喜欢saveWordsForCategorysaveWordsForPostssaveWordssaveWord

【讨论】:

    猜你喜欢
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 2021-11-05
    • 1970-01-01
    相关资源
    最近更新 更多