我如何返回承诺的价值,而不是返回承诺本身? (反应/还原)

时间:2018-07-05 20:14:21

标签: javascript reactjs redux promise fetch

我在一个化简器中遇到一个问题,在那里我可以轻松地将所有信息返回到前端,除了一个称为“ items”的数组,我需要进行一次额外的提取以获取更多数据。我在此获取操作中遇到的问题是,它最终会导致返回承诺而不是返回值。我的问题是我如何获得价值而不是承诺? (例如,通过阻止其他所有内容直到诺言解决,然后再将其发回)。

我在下面的代码中都进行了注释,希望可以更清楚地解释所有内容:

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

我希望我的问题很清楚,但是如果需要进一步的详细说明,请告诉我。

1 个答案:

答案 0 :(得分:0)

您不能从诺言的猫/错误处理程序中返回数据

如果两者都想发送数据,我建议包裹另一个将永远解决的承诺

return new Promise((res) => {
  //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
  getUpdatedItems(itemIds, items).then(result => {
    //result is the actual value I want
    res(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
    res(history.map(h => items.get(h.get('item'), null)));
  }).catch(error => {
    res(history.map(h => items.get(h.get('item'), null)));
  })
});