angry_kiwi angry_kiwi - 18 days ago 6
Javascript Question

javascript - redux thunk doesn't wait for any promise

I have an array like so

array =[ {message:'http://about.com'}, {message:'http://facebook.com'}]


I want to loop that array, at each item I will make request to server to fetch opengraph data then save the data back to array. This what I expect

array =[
{
message: { url:'http://about.com', title:'about'}
},
{
message:{ url:'http://facebook.com', title:'facebook'}
}
]


Then when it all finishes. I want to dispatch an action with payload is the expected array. Here is how I did it

return dispatch => {

let array =[ {message:'http://about.com'}, {message:'http://facebook.com'}]

let quests = array
.map( (item) => {
axios.get(getOpenGraphOfThisLink + item.message)
.then( result =>{
item.message = (result.data)
return result
})
})

Promise.all(quests).then( () => {
console.log( 'modified', array)
dispatch({
type : constant.GET_POST_COLLECTION_SUCCESS,
payload: array
})
// this dispatch function sends my original array instead of modified one.
})
}


The problem: the dispatch function in the code will send my original array to reducer instead of modified one. I want dispatch to send the new modified array. And I think it should it, shouldn't it?

Answer

Right now quests variable is just assigned by your original array, because the map function return void, but you need to return promises of each item to the quests, so just add return key word, so that your code be like this:

let quests = array
    .map( (item) => {
        return axios.get(getOpenGraphOfThisLink + item.message)
        .then( result =>{
            item.message = (result.data)
            return result
        })
    })