Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

javascript函数组合的时候参数相同怎样处理?

我现在需要对一个http超时进行重试,因为用的是rxjs,所以在重试之前会对取消之前的订阅,如果再次发送同样的请求也会取消之前的订阅

我一共写了三个方法, beforeRetryRequest(taskId), retryRequest(http, taskId), record(taskId, token)尝试用lodash的compose函数去组合这几个函数,但是我发现他们上一个执行输出的值不是下一个函数参数.

相关代码

let tasks = new Map();


const beforeRetryRequest = (taskId)  => {
    if (tasks.has(taskId)) {
         const task = tasks.get(taskId); 
         task.unsubscribe(); 
     }
     return http;
 }

const retryRequest = (http, taskId) => {  
    if (tasks.has(taskId)) {
        const task = tasks.get(taskId); 
        task.unsubscribe(); 
    }
    const token = defer(() => http())
            .pipe(retryWhen(errors => errors.pipe(delay(1500), take(5), tap(() => {
                console.log('retry ...')
            }))))
            .subscribe(
            data => console.log(data),
            err => console.log('error callback', err),
            complete => console.log('compelte' + complete)
     );
     return token
}

const record = (taskId, token) => {
     tasks.set(taskId, token)
}

你期待的结果是什么?实际看到的错误信息又是什么?

我想处理成对外只是暴露一个函数,我看了一些curry的知识,不知道对这个有没有帮助
本人才疏学浅,还望各位不吝赐教 谢谢啦~~


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

lodash 里面也没有 compose 方法啊?
你说的是redux里面的这个 compose 吧?

`compose = (...fns) => (...args) => fns.reduceRight((arg, fn) => fn.apply(null, arg), args)`

这玩意除了最近那个其他的参数只能是前一个返回值,所以得统一一下, 其实我不建议用这个,你的方法队列是确定的,没必要折腾,但是还是给你一个方案:

let tasks = new Map();


const beforeRetryRequest = (taskId) => {
    if (tasks.has(taskId)) {
        const task = tasks.get(taskId);
        task.unsubscribe();
    }
    return [taskId, http];
}

const retryRequest = ([taskId, http]) => {
    if (tasks.has(taskId)) {
        const task = tasks.get(taskId);
        task.unsubscribe();
    }
    const token = defer(() => http())
        .pipe(retryWhen(errors => errors.pipe(delay(1500), take(5), tap(() => {
            console.log('retry ...')
        }))))
        .subscribe(
            data => console.log(data),
            err => console.log('error callback', err),
            complete => console.log('compelte' + complete)
        );
    return [taskId, token]
}

const record = ([taskId, token]) => {
    tasks.set(taskId, token)
}

const compose = (...fns) => (...args) => fns.reduceRight((arg, fn) => fn.apply(null, arg), args)


export default compose(record, retryRequest, beforeRetryRequest)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...