我想獲取返回值,但始終得到未定義。從函數調用未定義的返回值Javascritpt
var hasNext;
es.search(nextQuery, function (err, data) {
if(data.hits.hits.length) {
return hasNext = true;
}
return hasNext = false;
});
我不知道如何得到任何返回值並在其他地方使用它?我需要使用這個返回值來驗證其他函數,但它似乎在範圍之內。
這是我的代碼:
functions.getRecentPost = function (req, res, next) {
.........
// This will get all the post
es.search(query, function (err, data) {
if(err) { // if error means no post and redirect them to create one
return res.redirect('/new/post');
}
....
content.hasPrevious = hasPreviousPage(_page, content.posts.length); // this function is okay
hasNextPage(_page, content.posts.length, function (data) {
content.hasNext = data;
});
res.render("index.html", content);
});
};
function hasNextPage (pageNum, totalPost, callback) {
es.search(query, function (err, data) {
if(data.hits.hits.length) {
return callback(true);
}
return callback(false);
});
};
那是因爲'es.search'是一個異步函數,所以它後面的所有內容都會在調用後立即執行,而不是在它返回時執行。任何依賴於es.search結果的邏輯都應該在設置hasNext的回調函數中進行。 –
@ go-oleg有無論如何,我可以定義爲一個全局值或我至少可以將它返回給另一個函數? – Ali
如果這段代碼片段屬於某個函數,那麼該函數本身也應該是異步的,並且應該將回調函數作爲一個參數,當它完成時調用它,類似於es.search'的工作方式。 –