gpt4 book ai didi

node.js - 如何从内联函数中获取变量

转载 作者:太空宇宙 更新时间:2023-11-04 01:15:27 24 4
gpt4 key购买 nike

假设我有一个函数:

function grabOldestJob() {
var client = mysql.createClient({
user: dbConfig['USER'],
password: dbConfig['PASS'],
});

client.query('USE '+dbConfig['DATABASE']);

client.query('SELECT url FROM '+dbConfig['JOB_TABLE']+' ORDER BY added ASC LIMIT 1 ',
function selectCb(err, results, fields, passed) {
if (err) {
throw err;
}
client.end();
fetchFeed(results[0]['url']);
}
);
}

我需要的是埋藏在内联函数中的 results[0]['url'] ,所以我要么想从该函数中获取该变量,以便我可以使用它返回 scrapOldestJob 函数,要么将另一个函数传递到内联函数中,以便我可以使用 results[0]['url'] 作为参数。

我对 Node.js 的概念非常陌生,并且想让我的代码尽可能“正确”。此函数是流程中的第一个函数,它从数据库中提取 url,将其传递到远程服务器,解析 xml feed,并将某些位存储在数据库中。我希望利用 Node “一次运行很多东西”的能力,我能够同时获取->解析->保存许多提要。对此的任何最佳实践提示也将不胜感激。

最佳答案

为此使用回调函数。

就像client.query(query,callback)函数一样。您传入数据和一个回调函数,如果处理完成,该回调函数就会被调用。对 fetchFeed(url,callback) 函数执行相同的操作。

...
client.end();
fetchFeed(results[0]['url'],function(result){
// here 'result' contains the fetched feed and can be stored into the database
});
...
<小时/>
function fetchFeed(url,cb){
// download feed here and call cb(downloaded_data) when finished, passing the downloaded data to the cb() function
}

看看:Understanding the node.js event loop

关于node.js - 如何从内联函数中获取变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10238849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com