2014-09-10 18 views
0

我想知道如何(如果可能)我可以創建相同的功能,具有完全相同的功能,但要用於回調或沒有它。這是與「通緝令效果」不工作的例子:如何編寫一個函數用於有或沒有回調的JavaScript?

function getUsers(req, res, onComplete) { 
    // If the user is not logged in send an error. In other case, send data 
    if (!req.session.session_id) { 
     if (typeof onComplete === 'function') { 
      onComplete({error: true, msg: 'You are not logged in'}); 
     } else { 
      res.json({error: true, msg: 'You are not logged in'}); 
     } 
    } else { 
     //Another similar code... 
    } 
} 

這不是因爲工作,如果我稱之爲「getUsers(REQ,RES)」,將typeof的onComplete總是功能,所以無法檢測到何時我打電話或不打回電。

確切的問題是,我可以從我的代碼中調用這個函數,以回調(正常呼叫,像getUsers(req, res, function(cb) {//Do something with cb});我也可以從一個AJAX調用在我的網站調用這個函數,像http://localhost:8080/api/getUsers,在這種情況下是什麼當它不起作用

在最後的情況下,我得到typeof onComplete === 'function'爲真,所以我從來沒有得到執行的其他部分我假設http調用完成的「請求」有更多的參數比req & res,這就是爲什麼onComplete是一個函數,而不是undefined。

通常的AJAX調用是這樣的(在客戶端的JavaScript):

function getAllUsers() { 
    $.ajax({ 
     url: '/api/getUsers', 
     type: 'GET', 
     success: function(data) { 
      // Remove item and set as main topic the assigned on the server 
      printUsers(data.users[0]); 
     }, 
     error: function(XMLHttpRequest, textStatus, errorThrown) { 
      alert(XMLHttpRequest.responseText); 
     } 
    }); 
} 

而且在我的Node.js的config.json調用最終函數定義的路線是這樣的:

{"path": "/api/getUsers", "method":"get", "callback": "api#getUsers"}, 

回答

3

如果調用getUsers沒有的onComplete值將被設置爲undefined 。然後你可以在你的函數中檢查這種情況。

function getUsers(req, res, onComplete) { 
    // Set onComplete to default call back if it is undefined 
    onComplete = onComplete || function(msg){ res.json(msg) }; 

    if (!req.session.session_id) { 
     onComplete({error: true, msg: 'You are not logged in'}); 
    } else { 
     //Another similar code... 
    } 
} 

這樣做

+0

嘛多種方式見http://www.markhansen.co.nz/javascript-optional-parameters/,似乎我是個白癡,因爲我再次測試我的代碼,現在它的工作原理。不知道爲什麼第一次它不工作,也許我這次寫了一些不同的東西。你的解決方案是優雅的...如果我只是每次都返回相同的值,並且我總是期待回調,但是我的情況是,如果最初的調用沒有回調,返回可能是res.json(所以我不會期望任何回調返回),或者如果我打電話回叫(我將等待返回)。 – Eagle 2014-09-10 11:54:02

+0

好吧,沒有工作,現在我已經做了一些替代測試,並且它不工作,「我需要」。主標題中有更多信息 – Eagle 2014-09-10 13:29:41

相關問題