2015-09-06 66 views
1

我對節點和回調是非常陌生的。我正在處理Nodeschool問題:使用回調函數按順序返回三個給定URL的數據。我將三個URL的結果放在一個對象中,以便按順序跟蹤它們。不過,我仍然拒絕測試,因爲我認爲,在我把所有的URL放入它之前,URL對象會被返回。節點回調中的意外令牌功能

TLDR:

以下是違規的功能。它一直告訴我「SyntaxError:意外的標記功能。」但是,當我在storeUrlconsole.log(urlObj[url])到它自己的功能,並把它稱爲的名字,我不認爲這是if語句後運行...

function storeUrl(url, info, function(url) { 
    // Only log after all the checking is done 
    console.log(urlObj[url]); 
}){ 
// add data to a dict? or something? 
// to keep track of them??? 
if(url == url1){ 
    urlObj[url1] = info; 
} 

if(url == url2){ 
    urlObj[url2] = info; 
} 

if(url == url3){ 
    urlObj[url3] = info; 
} 

} 

這裏是我的整個文件:

var http = require('http'); 
var bl = require('bl'); 
var url1 = process.argv[2]; 
var url2 = process.argv[3]; 
var url3 = process.argv[4]; 
var urlObj = {}; 
urlObj[url1] = ''; 
urlObj[url2] = ''; 
urlObj[url3] = ''; 


function firstUrl(callback, callback){ 
    getHttp(url1); 
    callback(url2); 
    callback(url3); 
} 

function startItOff(){ 
    firstUrl(function secondUrl(contents){ 
    getHttp(contents); 
    }, function thirdUrl(contents){ 
    getHttp(contents); 
    }); 

    // This is what I ultimately want: 
    // A log of the data of each URL, in order, on its own line: 
    for (item in urlObj){ 
     console.log(urlObj[item]); 
    } 
} 

////////////// 
// Above this line is ok, 
// now trying to retrieve the url only after 
// getting the right one. The getHttp shows 
// them in the right order, but retrieveHttp 
// doesn't have an order to it. 
///////////// 

function getHttp(url){ 

    middleman(url, retrieveHttp); 

} 

function middleman(url, callback){ 
    callback(url); 
} 

function retrieveHttp(url){ 


    http.get(url, function(res){ 

    res.setEncoding('utf8'); 
    res.pipe(bl(function(err,data){ 
     if (err) return Error('Error'); 
     storeUrl(url, data.toString(), callback); 

    })); 

    }); 
} 

function storeUrl(url, info, function(url) { 
    console.log(urlObj[url]); 
}){ 
    // add data to a dict? or something? 
    // to keep track of them??? 
    if(url == url1){ 
    urlObj[url1] = info; 
    } 

    if(url == url2){ 
    urlObj[url2] = info; 
    } 

    if(url == url3){ 
    urlObj[url3] = info; 
    } 

    // Also trying to log the data from the URLs here: 
    console.log(urlObj[url1]); 

} 

startItOff(); 

回答

1

這條線是一個語法錯誤:

function storeUrl(url, info, function(url) { 
// Only log after all the checking is done --> 

所以當節點表示,它的語法錯誤,它不是撒謊:)。當你定義一個函數的參數時,你不能包含這個函數。

這將是有效的語法:

function storeUrl(url, info, callback) { 
    console.log(url); 
    callback(); 
} 

我建議不要試圖瞭解節點和Javascript在同一時間。學習Javascript基礎和調試,然後回調,然後解決Node。

+0

怎麼會是這樣?:工作 'fs.readFile( 'movie.mp4',功能finishedReading(錯誤,movieData){ 如果(錯誤)返回console.error(錯誤) //做東西與電影數據 })' –

+0

因爲你沒有在那裏定義參數,你指定的回調代碼。 storeUrl行以'function'開頭,你的例子以'readFile'調用開始。當你開始時,這很讓人困惑。通常對於回調你不會指定一個名字。所以你可以把'finishedReading'離開那裏。 –