【发布时间】:2018-12-14 09:37:31
【问题描述】:
我在我的一个 reducer 中遇到问题,我可以随时返回前端的所有信息,除了一个名为“items”的数组,我需要进行额外的提取以获取更多数据.我在这个 fetch 中遇到的问题是它最终导致返回一个承诺而不是返回值。我的问题是如何获得价值而不是承诺? (例如,通过阻止其他所有内容,直到 promise 解决,然后将其发回)。
我在下面的代码中进行了评论,希望能更清楚地解释一切:
export const getItemsForHistory = createSelector(
[getAllHistory, getAllItems, getHistoryPage], (history, items, page) => {
let itemIds = `[a bunch of ids]`;
//this is the call I am making to fetch the additional data for "items"
//this return statement is sending back a promise and not a value
return getUpdatedItems(itemIds, items).then(result => {
//result is the actual value I want
return result;
}, error => {
//if the fetch fails, I would like to send a default value for "items"
//note, if I place this return outside of this entire promise and remove the promise, it works as expected with the default data
return history.map(h => items.get(h.get('item'), null))
}).catch(error => {
return history.map(h => items.get(h.get('item'), null))
})
}
)
//I would like for this method to run asychronously
const getUpdatedItems = async (itemIds, items) => {
let result = await fetchHistoryItemsDetail(itemIds);
return result;
}
const fetchHistoryItemsDetail = (itemIds) => {
let headers = {
"Content-Type": "application/json",
},
fetchUrl = `XXXXXXXXX`;
return fetch(fetchUrl, {
method: "POST",
headers: headers,
body: itemIds,
withCredentials: true,
crossDomain: true,
})
.then(response => {
return response.json();
})
.catch(error => {
throw error;
})
}
export const getSortedHistory = createSelector(
[getAllHistory, getItemsForHistory, getHistorySort, getHistoryPage], (history, items, sort, page) => {
//this is where items is ultimately retured to the front end but it is now a promise and not an array of data
//(from getItemsForHistory)
return sortedEntities(history, items, sort)
}
)
我希望我的问题很清楚,但如果需要进一步详细说明,请告诉我。
【问题讨论】:
-
你没有。你必须在整个过程中保持异步。
标签: javascript reactjs redux promise fetch