使用async.waterfall [英] Using async.waterfall

查看:358
本文介绍了使用async.waterfall的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用node.js和异步包。

I'm using node.js and the async package.

这是我的代码:

async.waterfall(
[
    function(callback) {
        var data = getSomeData();
        callback(null, data);
    },
    function(data, callback) {
        someFunctionThatNeedsData(data);
        callback(null, 'done');
    }
],
function(err, result) {
}
);

getSomeData 有一个异步HTTP请求可以抓取来自Web服务的一些数据。我想等到收到回复,然后返回该数据并将其传递给 someFunctionThatNeedsData

getSomeData has an asynchronous HTTP request that grabs some data from a web service. I'd like to wait until I get a response, and then return that data and pass it to someFunctionThatNeedsData.

我期望的是 getSomeData - 包括其内部的回调 - 必须在继续调用 someFunctionThatNeedsData

What I expected was that getSomeData -- including the callback inside of it -- would have to complete before moving on to invoke someFunctionThatNeedsData.

问题是,尽管在这里使用瀑布函数,数据在到达 someFunctionThatNeedsData 时未定义。

The problem is that, despite using the waterfall function here, data is undefined by the time it gets to someFunctionThatNeedsData.

此外,来自 console.log 我可以看到 getSomeData 的结尾是在 getSomeData内回调之前到达的甚至开始。

Additionally, from console.log I can see that the end of getSomeData is reached before the callback inside of getSomeData even begins.

我错误地使用瀑布,还是不是正确的工具吗?如果它不对,我可以使用什么来达到预期的效果呢?

Am I using waterfall incorrectly, or is it just not the right tool here? If it's just not right, what can I use to achieve the desired effect?

或者我必须辞职才能进行深度嵌套的回调(对于未来的工作,我并且必须通过将内联代码提取到命名函数来缓解它?

Or do I have to resign to having deeply nested callbacks (which, with future work, I will) and have to just mitigate it by extracting inline code into named functions?

推荐答案


getSomeData( )有一个异步的http请求,可以从Web服务中获取一些数据。

getSomeData() has an asynchronous http request that grabs some data from a web service.

这就是问题所在。执行流程已经继续回调并执行它。这就是异步函数的工作原理!

This is the issue. The execution flow already continued to the callback and executed it. This is how asynchronous functions work!

你必须将回调传递给 getSomeData ,它会在HTTP调用它请求完成。所以是的:您可能需要嵌套回调。

You have to pass the callback to getSomeData, which calls it once the HTTP request finished. So yes: You may need to nest the callbacks.

这篇关于使用async.waterfall的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆