[英]NodeJS + CoffeeScript, render coffeescript compiled js on request
[英]coffeescript with Request scoping
request = require('request')
auth =
url: ''
method: 'POST'
json:
credentials:
username: ""
key: ""
exports = exports ? this
request auth, (err, res, body) ->
exports.inside = body
console.log(exports.inside)
然后上面是帶有Node.js請求模塊的Coffeescript。 我無法弄清楚如何獲取請求函數內部的數據。 這一直是我應用程序的主要障礙。
謝謝!
**編輯**
Vadim Baryshev的代碼更新做到了! 非常感謝 :) !
您正在嘗試輸出exports.inside
然后再在request
函數回調中分配它。 因為request
功能是異步的。 您可以通過回調或事件獲取此函數的結果。
更新 :
request = require('request')
exports = exports ? this
getAuth = (callback) ->
auth =
url: ''
method: 'POST'
json:
credentials:
username: ""
key: ""
request auth, (err, res, body) ->
exports.inside = body
callback err, body
getAuth (err, body) ->
# here is exports.inside ready
console.log exports.inside
# also you can access body and request error arguments here
# body === exports.inside here
# err is request error (is null/undifined if request is successful)
請求函數完成后,它將觸發一個回調,這是您可以可靠訪問“ body”值的唯一位置。
您遇到的問題是,當console.log函數運行時,由於請求未完成,因此未觸發回調。
有關異步編程環境中程序流的更詳盡的描述,請參閱nodejs中使用fs.stat的問題 。
---編輯---例如:
考慮一下:
1: path='/tmp/file.txt'
2: result=''
3: fs.readFile path, (err,data) ->
4: throw err if err
5: result=data
6: console.log result
如果要跟蹤此操作,我們會發現執行順序為1,2,3,6,... 4,5,其中,由於光盤I / O的特性,省略號表示一些未知量時間。
因為讀取操作要花一些時間才能完成,而不是等待結果,所以我們提供了一個回調函數,該函數將在將來讀取文件內容時在某些不可預測的時刻調用,因此可以將其分配給'結果'。
當程序流到達第6行時,由於文件讀取操作尚未完成,因此尚未調用回調,因此未設置結果。
這就是異步編程的本質,我們可以將浪費的時間用於其他目的,而不是在繼續操作之前等待操作完成。
--- 2ND編輯---好的,根據您的要求,以下示例經過修改,可以正常工作。
request = require('request')
auth =
url: ''
method: 'POST'
json:
credentials:
username: ""
key: ""
exports = exports ? this
request auth, (err, res, body) ->
exports.inside = body
console.log(exports.inside)
請注意,正如已經多次描述的那樣,您無法在回調之外訪問請求的結果,因為您不知道請求何時完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.