从JavaScript内部回调函数保存值[重复]

时间:2022-02-28 09:51:44

This question already has an answer here:

这个问题在这里已有答案:

I realize JavaScript callbacks have been explained over and over, but I don't seem to find a way to save values from an inner callback function.

我意识到JavaScript回调已经反复解释,但我似乎没有找到一种方法来保存内部回调函数的值。

request.get('http://google.com', function(error, response, body){
    var $ = cheerio.load(body);
    // Process HTML here
    // How do I save the result from processing with a callback
}

// Or
var parse = function(error, response, body){
    // Process HTML here
    // Assign result to a variable or pass a callback to this function
};
request.get('http://google.com', parse);

I have multiple urls to process and I'd like to have one object summarizing the information afterwards.

我有多个网址要处理,我希望有一个对象在后面总结信息。

By saving I mean either assigning to a variable or saving to a file.

保存我的意思是分配给变量或保存到文件。

1 个解决方案

#1


0  

Remember that the callback will be called when the async operation completes (like a second thread), meaning that the code after request.get will have been already executed then and you can't use return to send values back.

请记住,异步操作完成后将调用回调(如第二个线程),这意味着request.get之后的代码已经执行,然后您无法使用return返回值。

The solution is to make all the process inside the callback or to have other functions. Instead of returning the value, just make and call next_function(the_return_value) (something like that).

解决方案是在回调中创建所有进程或具有其他功能。而不是返回值,只需调用next_function(the_return_value)(类似的东西)。

#1


0  

Remember that the callback will be called when the async operation completes (like a second thread), meaning that the code after request.get will have been already executed then and you can't use return to send values back.

请记住,异步操作完成后将调用回调(如第二个线程),这意味着request.get之后的代码已经执行,然后您无法使用return返回值。

The solution is to make all the process inside the callback or to have other functions. Instead of returning the value, just make and call next_function(the_return_value) (something like that).

解决方案是在回调中创建所有进程或具有其他功能。而不是返回值,只需调用next_function(the_return_value)(类似的东西)。