2017-01-23 123 views
0

當我從服務器獲得響應時,如何獲取此值?如何在node.js中獲取請求後返回值?

終端在運行時不會輸出任何信息。

console.log(a); 
 
function findMaxID() { 
 
    var a = needle.get(URL, function(err, res){ 
 
     if (err) throw err; 
 
     return 222; 
 
    }); 
 
    return a; 
 
}

+0

使用承諾? –

+0

@BelminBedak你能告訴我一個簡單的代碼嗎?我使用promisses很多次,但在這裏,在這個例子中我的承諾不起作用 –

+0

http://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to優惠可能會有所幫助。 – ste2425

回答

0

基本上,你不能真正return在單向函數將該值返回值。你能做的就是給你的findMaxID()功能的回調參數當數據被取出被稱爲:

function findMaxID(callback) { 
    needle.get(URL, function(err, res){ 
     if (err) throw err; 
     callback(res); 
    }); 
} 

然後調用它像這樣:

findMaxID(function(id) { 
    console.log('Max ID is : ', id); 
} 

您也可以返回承諾

function findMaxID() { 
    return new Promise(function (resolve, reject) { 
     needle.get(URL, function(err, res){ 
      if (err) reject(err); 
      resolve(res); 
     }); 
    }); 
} 

,並調用它像這樣:

findMaxID().then(function(id) { 
    console.log('Max ID is ', id); 
})