2017-09-08 43 views
0

如何重構下面的代碼?Javascript,Ember 2,如何重構承諾的代碼(也許還有異步/等待)

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)); 
      }) 
     ); 
     }) 
    ) 
); 
}); 

此外,我想了解如何避免許多功能時,我有以下的皮棉規則對這個代碼:

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

如何使用異步/ AWAIT?

+0

您如何使用此功能的響應?你甚至需要它嗎?什麼是'this.ok()'和'this.error()'? – Lux

+0

這樣的兩個小函數:'console.log(error)'。無論如何,問題是這個代碼。你會怎麼做? –

+0

'get()'有點混亂。在第一次和第二次使用時,它似乎是*異步*,而在第三次使用時它看起來是*同步*。這是什麼? –

回答

3

我認爲你可能會失去的最複雜的是通過壓扁數組數組。但是,如果您需要該代碼的結果,這將不起作用。不過,我想你只是想保存所有的單詞。

然後,我會做這樣的事情:

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())); 

但是,如果你真的需要這個結構我想起來拆分代碼成多個功能。像saveWordsForCategory,saveWordsForPosts,saveWordssaveWord