如何在节点中同步执行操作

时间:2017-05-26 07:00:45

标签: javascript express

我知道节点是关于异步的东西,但我想在串行模式下做事情如下:

制作api请求>将body xml转换为JSON.stringify>将字符串传递给模板。

request.get({url:url, oauth:oauth}, function(err, res, body){
    parseString(body, function(err, result){
        output = JSON.stringify(result);

        res.render('home', { title: 'Fantasy Home', 
                output: output });
    });
});

现在我想按顺序执行此操作,但是对于所有回调我都很困惑。

res.render不能嵌套在回调中,因为res对象不存在。将它放在外面是行不通的,因为它会在回调执行之前运行,所以你会得到“未定义”的输出。

必须有一种按顺序执行操作的方法。为什么一切都是回调?为什么这些函数不能只返回常规的非回调结果?

我该如何做到这一点?

3 个答案:

答案 0 :(得分:1)

其他人没有提及为什么res.render不起作用。 你可能有这样的事情:

app.get('/', function(req, res, next) { // You need the res here to .render

    request.get({url:url, oauth:oauth}, function(err, res, body){ // But you are using this res instead, which does not have the render method
        parseString(body, function(err, result){
            output = JSON.stringify(result);

            res.render('home', { title: 'Fantasy Home', 
                    output: output });
        });
    });
});

阅读代码中的注释。因此,您的解决方案是,使用请求处理程序中的res.render,将res回调中的request.get重命名为其他内容。

答案 1 :(得分:0)

你应该使用中间件,也许在节点中使用异步是更好的事情,但我会向你展示回调。强烈建议不要使用同步调用来阻止你的线程!由于node.js是单线程的。 library(data.table) CJ(location = df1$location, code = df2$code) 是一个回调,因此中间件不允许执行主路由功能(使用res.render),直到调用next()。您可以根据需要传递尽可能多的中间件。

next()

答案 2 :(得分:0)

如果我们使用同步代码,JavaScript是单线程的,那么这本身就是响应时间(node.js)和所有问题的一个大问题。由于事件循环的好处,所有东西都以回调方式实现。

您可以深入了解事件循环:https://youtu.be/8aGhZQkoFbQ(非常好的解释)

您可以对要实施的方案使用Promisification:http://bluebirdjs.com/docs/getting-started.html

request.get({url:url, oauth:oauth}, function(err, res, body) {
    // Note :: This is Promisified Function
    return parseString(body)
        .bind(this)
        .then(function(result) {
            output = JSON.stringify(result);

            res.render('home', {title: 'Fantasy Home', output: output });

            return true;
        })
        .catch(function(error)
        {
            // Error Handling Code Here
            // Then send response to client
        });
});

您可以使用以下方法实现promisified函数

function parseString(body) {
    var Promise = require("bluebird");

    return new Promise(function(resolve,reject) {
        // Your Parsing Logic here

        if(is_parsed_successfully) {
            return resolve(parsed_data);
        }

        return reject(proper_err_data);
    })
}