Javascript 使用函数和回调函数的Node.js
我在node.js和使用函数方面遇到了一些困难。我的问题是,当我调用一个函数时,node.js并没有等待它完成,结果我没有得到任何返回值。这就是我所拥有的Javascript 使用函数和回调函数的Node.js,javascript,node.js,callback,Javascript,Node.js,Callback,我在node.js和使用函数方面遇到了一些困难。我的问题是,当我调用一个函数时,node.js并没有等待它完成,结果我没有得到任何返回值。这就是我所拥有的 exports.handle = (event, context,callback) => { switch (event.request.type) { case "IntentRequest": console.log('INTENT REQUEST') switch(event.request.in
exports.handle = (event, context,callback) => {
switch (event.request.type)
{
case "IntentRequest":
console.log('INTENT REQUEST')
switch(event.request.intent.name)
{
case "MoveDown":
readpos()
}
}}
function readpos(){
var position = []
//this code parses an array and gets me x y values
return position }
我的问题是我最终得到一个空数组,因为node.js运行速度太快。我假设我必须对回调做些什么,但我不确定如何实现回调。我试着在callback上阅读在线教程,但所有这些都让我感到困惑,我似乎无法将在线资源所说的应用于我的感冒。我的主要语言是C++和Python。 < P>这很简单。你在回拨中处理它。让我们看看您的固定函数:
exports.handle = (event, context,callback) => {
switch (event.request.type)
{
case "IntentRequest":
console.log('INTENT REQUEST');
switch(event.request.intent.name)
{
case "MoveDown":
callback(readpos());
}
}
};
function readpos() {
var position = [];
//this code parses an array and gets me x y values
return position;
}
现在,当你调用句柄时,你只需这样调用它:
handle(event, context,
// This is your callback function, which returns when done
function(position){
// When readPos() has run, it will return the value in this function
var newPos = position + 1; ...etc...
});
当然,您的代码应该遵循约定。回调是为了返回错误和结果而设计的,所以您也应该考虑到这一点。但这只是回调的一般概念:您需要将回调用作
exports.handle = (event, context,callback) => {
switch (event.request.type)
{
case "IntentRequest":
console.log('INTENT REQUEST')
switch(event.request.intent.name)
{
case "MoveDown":
callback();
}
}}
用法
function readpos(){
var position = []
//this code parses an array and gets me x y values
Don't return here instead use the result directly or store into a global
}
handle(event,context,readpos);
我看到了线程的可能重复,这让我更加困惑。幸运的是,这并没有减少重复。我的意思是,我尝试按照他们所说的做,将我的readPos更改为readPosfunctionerr,data//compute data callbackdata,但是mereadPos仍然不起作用,因为它当前编码不接受回调。