2017-03-05 48 views
1

在此函數中,在內聯數組完成之前調用回調函數。我只能在內聯具有所有值時才能調用它?如何運行promise數組

function inlineSearch(search, callback) { 
    const inline = [] 

    mal.quickSearch(search).then(response => { 
     response.anime.forEach(anime => { 
      anime.fetch().then(json => { 
       inline.push(replyInline(json)) 
      }) 
     }) 
     .then(callback(inline)) 
    }) 
} 

response.anime是一個JSON對象數組指向另一個JSON對象,這就是爲什麼我需要把它牽回家,所以我可以有正確的JSON。

而且,replyInline是一個函數,它只接受json並返回另一個。

mal =我的動漫列表API

+2

你有沒有看着['Promise.all()'](https://開頭developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)? – nnnnnn

+1

順便說一句,你需要'Promise.all'和'repsonse.anime.map' –

+0

,最後'.then'保證是錯誤的,因爲'.then'需要一個函數作爲參數 –

回答

2

使用Array#mapPromise.all - 和沒有必要的inline VAR或者

如果必須使用回調,那麼下面應該工作

function inlineSearch(search, callback) { 
    mal.quickSearch(search) 
    .then(response => 
     Promise.all(response.anime.map(anime => 
      anime.fetch() 
      .then(json => replyInline(json)) 
     )) 
    ) 
    .then(results => callback(results)); 
} 

用法:

inlineSearch("whatever", function(results) { 
    // do whatever with results 
}); 

或者,不回調上面可以這樣寫:

function inlineSearch(search) { 
    // note the return 
    return mal.quickSearch(search) 
    .then(response => 
     Promise.all(response.anime.map(anime => 
      anime.fetch() 
      .then(json => replyInline(json)) 
     )) 
    ); 
} 

用法:

inlineSearch("whatever").then(results => { 
    // do whatever with results 
}); 
+0

非常感謝,沒有回調的代碼工程很好。你幫我解決了一件事,那是近五天我正在努力去理解的事情。 –