【发布时间】:2014-05-28 10:37:38
【问题描述】:
我有一个函数,其中有一个嵌套的回调函数结构。我希望第一个“母亲”函数在回调函数序列中计算后返回某个值。然而。它真的不起作用。这是代码的简化版本,您认为您可以帮忙吗?
console.log(finalResult());
function finalResult() {
var finalanswer = firstFunction(secondFunction);
function firstFunction (callback) {
var notion = 1;
callback(null, notion);
}
function secondFunction (err, notion) {
if (err) console.log(err);
var answer = notion + 1
return answer;
}
return finalanswer;
}
谢谢!
**更新 - 原始代码**
return getContexts(makeQuery);
function getContexts (callback) {
dbneo.cypherQuery(context_query, function(err, cypherAnswer){
if(err) {
err.type = 'neo4j';
return callback(err);
}
// No error? Pass the contexts to makeQuery function
return callback(null,cypherAnswer);
});
}
function makeQuery (err,answer) {
// Error? Display it.
if (err) console.log(err);
// Define where we store the new contexts
var newcontexts = [];
// This is an array to check if there are any contexts that were not in DB
var check = [];
// Go through all the contexts we received from DB and create the newcontexts variable from them
for (var i=0;i<answer.data.length;i++) {
newcontexts.push({
uid: answer.data[i].uid,
name: answer.data[i].name
});
check.push(answer.data[i].name);
}
// Now let's check if there are any contexts that were not in the DB, we add them with a unique ID
contexts.forEach(function(element){
if (check.indexOf(element) < 0) {
newcontexts.push({
uid: uuid.v1(),
name: element
});
}
});
return newcontexts;
}
【问题讨论】:
-
你试过
return callback(null, notion)吗? -
请发布完整代码..你在哪里定义
secondFunction,你怎么称呼finalResult() -
对不起,我在简化时打错了。实际上 makeQuery = secondFunction
-
我刚刚谈到了早已逝去的 JavaScript 开发人员的精神,他们告诉我您正试图从异步函数返回。我的精神力量是否到位?
标签: javascript node.js callback