对于这两个功能:
function isSuspended (status){
if(status === 'suspended'){
return true;
}
return false;
}
function isSubscribed(status){
if(status === 'subscribed'){
return true;
}
return false;
}
使用Nodejs:
1-如何通过回调将两个函数合并为一个函数?
2-在这种情况下使用回调有什么好处?
答案 0 :(得分:0)
这里您不需要使用回调,只需按以下方式将它们合并即可:
function isSuspendedOrSubscribed(status) {
return (status === 'suspended') || (status === 'subscribed');
}
console.log(isSuspendedOrSubscribed('suspended'));
console.log(isSuspendedOrSubscribed('subscribed'));
console.log(isSuspendedOrSubscribed('random'));
在特定事件发生后需要执行特定操作时使用回调。例如:
setTimeout(()=> console.log('I am needed as a callback function to be executed after the timer') ,1000)
因此,这对于连接到网络或连接数据库(异步操作)也很有用
答案 1 :(得分:0)
Nodejs中的回调用于处理函数的异步活动。在任务完成时调用回调函数。
在您的情况下,我们不需要回调,但是如果您愿意,我们可以使用回调:
/*Here `status` could be `suspended` or `subscribed` and
callback is an function reference for calling
argumentative function which is available as a `handleSuspendOrSubscribe` parameter.*/
let handleSuspendOrSubscribe = (status, callback)=>{
if(status == 'suspended' || stataus == 'subscribed'){
callback(null, true); // callback first parameter must be error and 2 must be success, It is called `error first callback`
}else{
callback(true, null);
}
}
Now I am going to call handleSuspendOrSubscribe function like
handleSuspendOrSubscribe('suspended', function(err, success){
err ? console.log('Error: ', err) : console.log('Success: ', success);
})