How can I refactor the code below?
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));
})
);
})
)
);
});
Also I would like to understand how to avoid having many functions when I have the following lint rule on this code:
[eslint] Use named functions defined on objects to handle promises (ember/named-functions-in-promises)
How can I use async/await?
I think the most complexity you can lose is by flatten the array of arrays. However this will not work if you need the result of that code. However I assume you just want to save all words.
Then I would do something like this:
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()))});
or with async functions:
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()));
However if you really need this structure I would split your code up into multiple functions. Like saveWordsForCategory
, saveWordsForPosts
, saveWords
and saveWord
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.