2017-09-22 80 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);