nodejs-tw / ama

Ask me anything!
MIT License
31 stars 1 forks source link

在Request中如果要從網頁中提取字串到變數,該如何操作? #5

Closed flyinglimao closed 7 years ago

flyinglimao commented 8 years ago

感謝使用 Node.js Taiwan AMA,以下附上簡單提問範例供參考,請把內容改成你自己遇到的問題

目的

我希望從網頁中取得字串到其他地方用,可是因為閉包所以變數傳不出來,有其他方法嗎

使用的工具

Ubuntu 14.04 Node v0.10.25

操作流程

遇到的問題

我不知道如何把東西抓出來

嘗試過的解法

我想不到解法QAQ 可是因為Request在一個Function內,要作為Function的回傳值,所以沒辦法在Request的Function做動作

程式碼

下面附上我的程式碼以及我遇到的錯誤

程式碼

var out = '';
request('http://****.***', function(err, res, body){
    out += body;
}
console.log(out);

錯誤

undefined
chentsulin commented 8 years ago

這是非同步的典型問題

在包含 callback 的程式時,程式並不如你所想是從上到下

因為 console.log(out); 的時間比下面這個 callback 早執行

function(err, res, body) {
  out += body;
}

但理論上你的程式碼應該會印出 空字串 而不是 undefined,我有什麼誤會嗎?

你應該把要做的事情在 callback 做掉

request('http://*.', function(err, res, body) {
  var out = '';
  out += body;
  console.log(out);
}

可以參考下面這個的執行狀況

setTimeout(function() {
  console.log('後出來');
}, 0);
console.log('先出來');

詳細可以研究 event loop

比較進階可以研究 promise

new Promise(function(resolve, reject) {
  request('http://*.', function(err, res, body) {
    if (err) {
       reject(err);
    } else {
       resolve(body)
    }
  }
})
.then(function(body) {
  console.log(body);
});
flyinglimao commented 8 years ago

我修改成這樣

var out = 'Out = ';
request('http://*.', function(err, res, body){
    out += body;
    console.log(out);
}
console.log(out);

輸出結果為 undefined、'Out = undefined'

似乎不是Callback的非同步問題?

chentsulin commented 8 years ago
var out = 'Out = ';
request('http://*.', function(err, res, body){
    out += body;
    console.log(out);
});
console.log(out);

在我的電腦上 run 是

Out = undefined 
Out = undefined

這代表在 url 是不能 resolve 的情況下 callback 是同步執行的

flyinglimao commented 8 years ago

噢抱歉

我找到問題點了,值給錯所以 body 是 undefined

謝謝

maso0310 commented 6 years ago

後來是怎麼改的呢?