redux thunk - 承诺完成后如何在嵌套数组中调度数据

时间:2016-11-24 17:07:17

标签: javascript promise redux-thunk

我想将newArray中的所有“默认文本”变为“新文本”。然后使用“新文本”调度数组。问题是调度功能正在调度'默认文本'。看起来它不等待承诺。我的承诺设置在下面的代码中有什么问题?

return dispatch => {
    let newarray =[ 
        { post:[ {message:'default text'}, {message:'default text'}] }
    ]
    let quests = newarray.map( (i) => {
        return i.post.map( (item) => {
            return axios.get(someLink).then( result =>{
                item.message = 'new text'
                return result
            })
        })
    })

    Promise.all(quests).then( () => {
        dispatch({
            type: constant.GET_SUCCESS,
            payload: newarray
        })
    }).catch( () =>{
        console.log('no result')
    })
}

2 个答案:

答案 0 :(得分:1)

您的输入数据结构如下:

[
    {
        post: [
            {message:'default text'},
            {message:'default text'}
        ]
    }
]

您的代码将其转换为:

[
    [
        Promise<Axios>,
        Promise<Axios>
    ]
]

所以在外层,没有办法知道内心的承诺何时结束。我们需要额外的承诺层来将这些信息传递到对象图上。基本上,我们需要:

Promise<[
    Promise<[
        Promise<Axios>,
        Promise<Axios>
    ]>
]>

所以当所有内部承诺都能解决时,顶级承诺可以解决。执行此操作的代码看起来非常相似:

return function () {
    var newarray = [{ post: [{ message: 'default text' }, { message: 'default text' }] }];

    return Promise.all(newarray.map(function (i) {
        return Promise.all(i.post.map(function (item) {
            return axios.get(someLink).then(function (result) {
                item.message = 'new text';
            });
        }));
    })).then(function () {
        return {
            type: constant.GET_SUCCESS,
            payload: newarray
        };
    }).catch(function (error) {
        return {
            type: constant.GET_ERROR,
            payload: 'no result ' + error
        };
    });
};

如果您认为可以提高清晰度,我可以使用箭头功能(我不会):

return () => {
    var newarray = [{ post: [{ message: 'default text' }, { message: 'default text' }] }];

    return Promise.all(newarray.map( i => Promise.all(
        i.post.map( item => axios.get(someLink).then( result => {
            item.message = 'new text';
        }) )
    ))).then( () => ({
        type: constant.GET_SUCCESS,
        payload: newarray
    })).catch( (error) => ({
        type: constant.GET_ERROR,
        payload: 'no result ' + error
    }));
};

一般说明:我已从您的代码中删除了回调函数。它与承诺从其中调用代码延续回调背后的哲学相矛盾。

而不是这样做(基本上是你的代码):

function bla(callback) {
   asyncFunction().then(someProcessing).then(callback);
}

这样做:

function blaAsync() {
   return asyncFunction().then(someProcessing);
}

请注意第二个变体不再对其调用者有任何依赖性。它只是执行其任务并返回结果。调用者可以决定如何处理它:

blaAsync().then(function (result) {
   // what "callback" would do
})

答案 1 :(得分:0)

嵌套,异步和克隆(或模仿)的要求使这有点棘手:

您可以将所需的数组构建为外部变量:

function getMessagesAndDispatch(array) {
    try {
        let array_ = []; // outer variable, mimicking `array`
        let outerPromises = array.map((a, i) => {
            array_[i] = { 'post': [] }; // mimicking `a`
            let innerPromises = a.post.map((item, j) => {
                array_[i].post[j] = {}; // mimicking `item`
                return axios.get(getOpenGraphOfThisLink + item.message).then(result => {
                    array_[i].post[j].message = result.data;
                }).catch((e) => {
                    array_[i].post[j].message = 'default text';
                });
            });
            return Promise.all(innerPromises);
        });
        return Promise.all(outerPromises).then(() => {
            dispatch({
                'type': constant.GET_SUCCESS,
                'payload': array_
            });
        }).catch((e) => {
            console.log('no result');
            throw e;
        });
    } catch(e) {
        // in case of a synchronous throw.
        return Promise.reject(e);
    }
}

或者,可以省去外部变量并允许承诺传达数据:

function getMessagesAndDispatch(array) {
    try {
        let outerPromises = array.map(a => {
            let innerPromises = a.post.map((item) => {
                return axios.get(getOpenGraphOfThisLink + item.message).then(result => {
                    return { 'message': result.data }; // mimicking `item`
                }).catch((error) => {
                    return { 'message': 'default text' }; 
                });
            });
            return Promise.all(innerPromises).then((items_) => {
                return { 'post': items_ }; // mimicking `a`
            });
        });
        return Promise.all(outerPromises).then((array_) => {
            dispatch({
                'type': constant.GET_SUCCESS,
                'payload': array_ // mimicking `array`
            });
        }).catch((e) => {
            console.log('no result');
            throw e;
        });
    } catch(e) {
        // in case of a synchronous throw.
        return Promise.reject(e);
    }
}

除了我的错误,两个版本都应该有效。

如果需要,可以更全面地注入错误的默认值。