2015-12-17 178 views
2
exports.index = function(req, res) { 
moviedb.indexMovie() 
.then(x => { 
    Movie.findAsync() 
     .then(responseWithResult(res)) 
     .catch(handleError(res)) 
     } 
) 
}; 

function responseWithResult(res, statusCode) { 
    statusCode = statusCode || 200; 
    console.log("Populating Response"); 
    return function(entity) { 
    if (entity) { 
     res.status(statusCode).json(entity); 
    } 
    }; 
} 

上面的代碼工作得很好,responsewithresult函數中的返回函數使用.then響應填充。但是,我正在嘗試並嘗試這個,但它沒有奏效。請解釋爲什麼?然後調用Javascript匿名函數

exports.index = function(req, res) { 
    moviedb.indexMovie() 
    .then(x => { 
     Movie.findAsync() 
     .then(x => {responseWithResult(res)}) // <-- this doesn't work 
     .catch(handleError(res)) 
    }) 
}; 

回答

0

它不工作,因爲

.then(responseWithResult(res)) 

傳遞的responseWithResult(其是最終返回值的函數)的函數then結果,而

x => {responseWithResult(res)} 

邏輯上像

function(x) { 
    responseWithResult(res); 
} 

當你把那裏面then(...),沒有任何返回。

可以修復與

then(x => responseWithResult(res)) 

這就好比

function(x) { 
    return responseWithResult(res); 
} 

,但真的是你應該折射整個功能,更好地利用的承諾,並且必須在一個乾淨的代碼結束:

exports.index = function(req, res) { 
    moviedb.indexMovie() 
    .then(() => Movie.findAsync()) 
    .then(movie => responseWithResult(movie, res)) 
    .catch(() => handleError(res)) 
}; 

function responseWithResult(entity, res, statusCode) { 
    statusCode = statusCode || 200; 
    console.log("Populating Response"); 
    res.status(statusCode).json(entity); 
} 
3

因爲你返回undefined,加return之前responseWithRest來電或刪除它周圍的{} s到使它的表達箭頭功能。

承諾通過返回值工作。

你的第一個例子也不排序操作。函數立即被調用。

+0

我得到了第一部分。但是,請您詳細說明「不按序列操作」的含義。 – shiv

+0

@本傑明是正確的。請參閱文檔示例:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Shorter_functions – Nirus

+0

我現在瞭解箭頭操作位。本傑明談到的排序是什麼?我該怎麼做,有什麼好處? – shiv