2017-12-20 27 views
1

私は現在、あるnode.jsモジュールから別のnode.jsモジュールに変数値を取得しようとしています。これは私の現在の問題である:非同期http-request、node.jsモジュールと変数

私は、HTTPS要求を経由してのREST APIからデータを取得しています:

// customrequest.js 
 

 
sendRequest(url, function(data, err) { 
 
if(err) { 
 
    console.log('--- Error ---'); 
 
    console.log(err); 
 
} 
 
else { 
 
    console.log('--- Response ---'); 
 
    console.log(data); 
 
    // output: data 
 
    return data; 
 
} 
 
module.exports = { sendRequest }

そして、私のindex.jsファイル:

// index.js 
 
let sendRequest = require('./customrequest'); 
 
let req; 
 
req = sendRequest('google.com'); 
 
console.log(req); 
 
// output: undefined 
 
// how can I get the variable set, when request is getting data in response?

APIへのリクエストには応答に時間がかかることを完全に理解しています。 1つの解決策は、すべてを1つのjsファイルに入れることです。しかし、私のプロジェクトが時間が経つにつれて大きくなるので、モジュラーアプローチは私の後藤解決策です。これを解決する方法に関する提案はありますか?

+0

私は遭遇しました、それはmodules.exportの問題ではありませんが、リクエストからの遅延戻りのことです。どのようにこれを解決することができますか? –

+0

http-requestメソッドはどこですか? ところで、REST APIリクエストからの着信結果をログに記録するには、コールバックを使用する必要があります。 – TamirNahum

+0

sendRequest(url、function(data、err)...ここでは、読みやすさのためにこの名前を付けましたが、これは基本的にnode-fetch(fetch()...)で行われました。 –

答えて

0

ノードはこの状況でコールバックを使用します。

// customrequest.js 
 

 
sendRequest(url, callback) 
 
module.exports = { sendRequest }

// index.js 
 
let sendRequest = require('./customrequest'); 
 
let req = sendRequest('google.com', function (data, err) { 
 
    if (err) { 
 
    //handle error here 
 
    } 
 
    console.log(data); 
 
}; 
 
// output: undefined 
 
// how can I get the variable set, when request is getting data in response?

0

ありがとう:このような何かを試してみてください。私が遭遇する問題は多少異なります。私はこのコードスニペットを使って解決しました。非同期と待機を使用しています。

// request.js 
 

 
const fetch = require('node-fetch') 
 

 
async function myRequest (somestring) { 
 
    try { 
 
     let res = await fetch('https://api.domain.com/?endpoint='+somestring) 
 
     if (res.ok) { 
 
     if (res.ok) return res.json() 
 
     return new Error (res.status) 
 
     } 
 
    } catch (err) { 
 
     console.error('An error occurred', err) 
 
    } 
 
} 
 

 
module.exports = { myRequest } 
 

 

 

 

 
// index.js 
 

 
const request = require('./requests') 
 
const myRequest = request.myRequest 
 

 
let myVar; 
 

 
myRequest('somestring') 
 
    .then(res => myVar = res.result) 
 

 

 
setInterval(() => { 
 
    myRequest('somestring') 
 
     .then(res => myVar = res.result) 
 
    console.log(myVar) 
 
    }, 1000)

非同期機能との約束を返し待ちます。この約束は、解決されると変数に代入されます。

関連する問題