2017-09-22 79 views
-2

我在使用函数时遇到了node.js &的一些问题。我的问题是当我调用一个函数时,node.js并没有等待它完成,我最终没有得到任何回报值。这是我所拥有的使用函数和回调的Node.js

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运行得很快。我假设我必须做一些回调,但我不确定如何实现回调。我试着在线阅读在线教程,但他们都让我困惑,而且我似乎无法应用网上资源对我的感冒所说的话。我的主要语言是C++ & Python。

+0

的可能的复制[如何使一个函数等到回调有被称为使用node.js](https://stackoverflow.com/questions/5010288/how-to-make-a-function-wait-until-a-callback-has-been-called-using-node-js) –

+0

我已经看到了这个线程,它让我更加困惑。 – Continuum

+0

幸运的是,它并没有减少重复次数。 –

回答

0

这很简单。你在回调中处理它。让我们来看看你的固定功能:

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... 
}); 

当然,你的代码应该遵循惯例。回调函数旨在返回错误和结果,因此您也应该考虑到这一点。但是,这是回调的只是一个总的想法:)

0

您需要使用一个回调作为

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);