从批处理异步操作返回值 [英] Return value from batch async operation

查看:120
本文介绍了从批处理异步操作返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小型库,它应该运行几个异步操作并返回一个包含这些操作结果的对象,但解释器要么说该函数不是构造函数,要么当它接受构造函数时,该操作返回一个空对象。我认为我的问题与我的变量范围有关,但也许可能会更糟。



我尝试了什么:



代码本身看起来像这样

I have a small library that should run a couple of async operations and return an object containing the result of those operations but the interpreter either says the function is not a constructor or when it accepts the constructor, the operation returns an empty object. I think my problem has to do with my variable scoping but maybe it could be worse.

What I have tried:

The code itself looks like this

var render = {username: '', available: '', orders: '', frequent: ''},
attachModule = 1;

 function OnIndexLoad (username) {

this.endRes = function (username) {
    render.username = username;
    console.log(render)
    return render;
};

this.init = function (username, current) {
    var utilMap =    {

    1: function (index) {
        http.get({port: '1717', path: '/admin/', headers: {Accept: 'text/html'}}, function(res) {
        var temp = ''
        res.setEncoding('utf8');

        res.on('data', function (chunk) {
            temp += chunk;
        }).on('end', function() {
    // add result of async operation
            render.available = temp
            index++
        })

    }).on('error', function(e) {
            console.log(e)
        });
    },

    2: function(index) {
        http.get('http://localhost:1717/admin/page=20',  function(res) {

        var temp = ''
        res.setEncoding('utf8');

        res.on('data', function (chunk) {
            temp += chunk;
        }).on('end', function() {
    // add result of async operation
            render.orders = temp;
            index++
        })
    }).on('error', function(e) {
            console.log(e)
        });
    },

    3: function(index) {
        ordersModel.find({}, , function (err, orders) {
        if (err) throw err;

// ignore this whole bit but look out for the function's last line
        var hashMap = [], returnArr = [];

        orders.forEach(function (order) {
            hashMap.push(order.toObject()['food'].split(","));
        })

        hashMap.reduce(function(a, b) {
            return a.concat(b)
        }, []).forEach(function(item) {

            if ((k = returnArr.findIndex(function(elem) {
                return elem[0] == item;
            })) != -1) {
                returnArr[k][1]++;
            }
            else returnArr.push([item, 1]);
        })

        hashMap = [], returnArr = returnArr.sort(function(a, b) {
            return b[1] - a[1];
        }).slice(0, 5).forEach(function(elem) {
            hashMap.push({name: elem[0], counter: elem[1]})
        });
    // add result of async operation
        render.frequent = component("frequent", hashMap); // here
        index++;
    })
    }
    }; // close util map

// the important part
    var itemsToReturn = Object.keys(render).filter(e => e != 'username');
    utilMap[current](current);

    if (attachModule < itemsToReturn.length) {
            this.init(current, username) // does not recurse and incrementally perform async ops
        }
        else this.endRes(username);
}

this.init(attachModule, username)
}

exports = OnIndexLoad





然后,在调用脚本的中间件中,即需要此库的index.js ,我有,





Then, in a middleware from the calling script i.e the index.js requiring this library, I have,

var onIndexLoad = require("./lib/index-load");
new onIndexLoad(req.session.username);





我以为这样调用它会为我公开加载的对象 - 这样的事情



{key1:resultOfOperation1,key2:resultOfOperation2,key3:resultOfOperation3}



但是这样调用它只会暴露错误。如何仅在 render 对象准备好导出时才调用 endRes



I thought calling it that way will expose the loaded object for me--something like this

{key1: resultOfOperation1, key2: resultOfOperation2, key3: resultOfOperation3}

But calling it that way only exposes errors. How do I call the endRes only and only when the render object is ready to be exported?

推荐答案

当你不理解你的代码在做什么或为什么它做它的作用时,答案是调试器

使用调试器查看代码正在执行的操作。只需设置断点并查看代码执行情况,调试器允许您逐行执行第1行并在执行时检查变量,这是一个令人难以置信的学习工具。



调试器 - 维基百科,免费的百科全书 [ ^ ]

JavaScript调试 [ ^ ]

Chrome DevTools  | 网络  |  Google Developers [ ^ ]



调试器在这里向您展示您的代码正在做什么,您的任务是与它应该做什么进行比较。

没有在调试器中魔术,它没有发现bug,它只是帮助你。当代码没有达到预期的效果时,你就会接近一个错误。
When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute, it is an incredible learning tool.

Debugger - Wikipedia, the free encyclopedia[^]
JavaScript Debugging[^]
Chrome DevTools  |  Web  |  Google Developers[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.


这篇关于从批处理异步操作返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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