流星(光纤)循环和回调 [英] Meteor (Fibers) loop and callback

查看:83
本文介绍了流星(光纤)循环和回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

流星纤维同步模式让我发疯。这是一个简单的代码示例:

Meteor fibers "sync" mode is driving me crazy. Here is a simple code example :

var feedsData = feeds.fetch(); // [{_id: "1234"}, {_id: "6789", url: "http://...."}]
for(var i = 0, len = feedsData.length; i < len; i++) {
    var feed = feedsData[i];
    parser.parseURL(feed.url, function(err, out){
        console.log(feed._id, i); // outputs "6789" and "2" each times
    });
}

我不明白如何使这项工作。循环结束后调用回调,但是应该保留内部内部变量(如feed)......而它们不是。

I don't understand how to make this work. The callback is called after the loop is over, but the internal internal variables such as feed should be preserved... and they are not.

解析的url是好的(第一个,然后是第二个),但后来我无法更新我的数据,因为我在回调中没有好的_id。

The url parsed are good (the first one, then the second one), but then i can't update my data since I don't have the good _id in the callback.

想要的输出将是:12340和67891,而不是67892两次......
你将如何在流星/光纤代码中做到这一点?

The wanted output would be: "1234" "0" and "6789" "1", not "6789" "2" both times... How would you make this in Meteor / Fiber code ?

推荐答案

在光纤中做到这一点的另一种方式(它可能比我上面发布的未来答案更好):

Another way to do it in the "fiber"(and it is probably better than the answer with "future" I posted above) :

var feedsData = feeds.fetch(); // [{_id: "1234"}, {_id: "6789", url: "http://...."}]
Fiber(function() {
    var fiber = Fiber.current;
    for(var i = 0, len = feedsData.length; i < len; i++) {
        var feed = feedsData[i];
        parser.parseURL(feed.url, function(err, out) {
            console.log(feed._id, i);
            if(err) return fiber.throwInto(err);
            fiber.run();
        });
        Fiber.yield();
        console.log('here', i);
    }
    console.log('there');
}).run();
console.log('and there');

输出将是:

"and there"
"1234" "0"
"here" "0"
"6789" "1"
"here" "1"
"there"

请注意,Fiber功能中的所有内容都是自己执行的光纤好像是异步,这就是为什么和那里首先出现的原因

Note that everything in the Fiber function is executed in its own fiber as if it was asynchrone, which is why "and there" is outputed first

这篇关于流星(光纤)循环和回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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