Javascript,Ember 2,如何重构这个承诺代码(也许还有async / await)

时间:2017-09-08 21:48:15

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

我如何重构下面的代码?

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)

如何使用async / await?

1 个答案:

答案 0 :(得分:2)

我认为你可以失去的最复杂的是通过压平数组数组。但是,如果您需要该代码的结果,这将不起作用。但是我假设您只想保存所有单词。

然后我会做这样的事情:

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一样。