我一直在与下面的代码作斗争。我实际上想知道如何在主函数“myfunc()”中返回内部对象“result”的值。
function myfunc(){
con.connect(function(err){
con.query(q,function(err){
var result = 'mY Result';
});
});
}
我只想将“结果”分配给“myfunc()”。谢谢
最佳答案
您可以采取以下方法:
// add async here to denote the method as awaitable to callers
async function myfunc(){
// Wrap the inner logic with a promise. This allows you
// return a result, when it is available
return new Promise((resolve) => {
con.connect(function(err){
con.query(q,function(err){
// Once the inner functions complete, and
// a result is available, we return that
// result to external code by passing the
// result to the 'resolve' function like
// so:
var result = 'mY Result';
resolve(result)
});
});
})
}
现在,根据您的项目设置方式,您通常有两种调用 myfunc()
的选项:
// Option #1
const queryResultOption1 = await myfunc()
// Option #2
myfunc().then(function(queryResult) {
// Use queryResult here
})
一般来说,选项 #2 是“较旧”的做事方式,但提供更广泛的支持,而选项 #1 是“较新”的方式,倾向于更容易阅读、推理和使用的代码,等等
更新
请注意,使用选项#2
时存在一些限制。例如,您只能在 async
方法的上下文中使用 await
关键字调用 myfunc()
。
换句话说,这意味着如果您调用它的位置未标记为async
,则您不能直接调用await myfunc()
。例如,要直接在 Nodejs 入口脚本中使用此方法,您需要执行以下操作:
(async function () {
const result = await myfunc()
})()
希望这有帮助!
关于javascript - 将对象值返回给父函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52031316/