简体   繁体   English

Node.js:使用回调合并功能

[英]Nodejs : merging functions using callbacks

For these two functions : 对于这两个功能:

  function isSuspended (status){
    if(status  === 'suspended'){
        return true;
    }
    return false;
 }


 function isSubscribed(status){
    if(status  === 'subscribed'){
        return true;
    }
    return false;
 }

Using Nodejs : 使用Nodejs:

1- How can i merge both functions into one function with callback? 1-如何通过回调将两个函数合并为一个函数?

2- What is the benefit of using callbacks in such situation? 2-在这种情况下使用回调有什么好处?

Here you don't need to use a callback, you can simply merge them in the following manner: 在这里,您不需要使用回调,只需按以下方式合并它们:

 function isSuspendedOrSubscribed(status) { return (status === 'suspended') || (status === 'subscribed'); } console.log(isSuspendedOrSubscribed('suspended')); console.log(isSuspendedOrSubscribed('subscribed')); console.log(isSuspendedOrSubscribed('random')); 

Use callback when a certain action needs to be performed after a certain event happened. 当特定事件发生后需要执行特定操作时,请使用回调。 For instance: 例如:

 setTimeout(()=> console.log('I am needed as a callback function to be executed after the timer') ,1000) 

Thus could also be useful for things like reaching out to the web or connecting to a database (async operations) 因此,对于诸如访问Web或连接数据库(异步操作)之类的操作也可能有用。

Callback in Nodejs is used to handle the asynchronous activities of the function. Nodejs中的回调用于处理函数的异步活动。 A callback function is called at the end of the completion of the task. 在任务完成时调用回调函数。

In your case we don't need callback but if you want then we can use callback like: 在您的情况下,我们不需要回调,但是如果您愿意,我们可以使用如下回调:

/*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);
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM