【问题标题】:How do I synchronize my function calls in node js?如何在节点 js 中同步我的函数调用?
【发布时间】:2015-12-15 12:38:29
【问题描述】:

这是我的 routes.js

app.route('/api/book/:id')
        .get(function(req,res){
            var id=req.params.id;
            bookapi.getBookDetails(id,res);
        });

这是它调用的函数

scope.getBookDetails=function(bookId,res){
    console.log('unnecessary thing@@');
    //var bookId=req.params.id;
    connection.query({
        sql:"SELECT name,description FROM books WHERE books.id=?",
        values:[bookId]
    },
    function (err,results) {
        if(err) throw err;

        if(results.length>0){
            var x=scope.getGenre(bookId);
            console.log(x +"hello");
            res.send(JSON.stringify(results)+scope.getAuthors(bookId)+scope.getGenre(bookId));
        }
    }
    )
}

我也在使用 angular,所以当一个 get 请求被发送到 '/books/:bookId' 时,它会调用这个控制器:

函数($scope,$routeParams,$http){

$http.get('/api/book/'+$routeParams.bookId).success(function(bookdetails){
            $scope.bookdetails=bookdetails;
        })
    }

这是我的服务器端控制台:

unnecessary thing@@
undefinedhello
GET /api/book/1 304 16.577 ms - -

在我的客户端控制台中,我得到了响应

[{"name":"The Alchemist","description":""}]undefinedundefined

在我的服务器端控制台中,在 id=1 甚至可以通过“/api/book/1”之前调用 getBookDetails。为什么会这样?为什么不同步?我应该为此学习异步吗?

谢谢

【问题讨论】:

    标签: javascript angularjs node.js


    【解决方案1】:

    req.params.id 分配给变量id 始终是同步的,因此问题不存在。问题可能在于getGenregetAuthors 是异步的,因此必须将依赖于它们的结果的任何内容移动到回调函数中。

    一种更简单的方法是使用 Promise。一个非常有趣的学习 JavaScript 承诺库是 bluebird。它应该会让你的事情变得更容易。

    app.route('/api/book/:id')
        .get(function(req,res){
            var id=req.params.id;
            bookapi.getBookDetails(id).then(function(result){
                res.send(result)
            });
        });
    
    scope.getBookDetails=function(bookId){
        console.log('unnecessary thing@@');
        //var bookId=req.params.id;
        return Promise.promisify(connection.query)({
            sql:"SELECT name,description FROM books WHERE books.id=?",
            values:[bookId]
        })
        .then(function (results) {
            if(results.length>0){
                return Promise.props({
                    // getGernre should return a promise just like this function.
                    // if it accepts a callback, you can do
                    // Promise.promisify(scope.getGenre) and use that instead
                    genre: scope.getGenre(bookId),
                    authors: scope.getAuthors(bookId),
                    results: results,
                })
            }
        })
        .then(function (dict){
            if(dict){
                console.log(dict.genre +"hello");
                return JSON.stringify(dict.results)+dict.authors+dict.genre;
            }
        })
    }
    

    【讨论】:

    • 感谢您的宝贵时间。 promise 似乎是一个可行的解决方案。但是,我仍然不明白为什么在发送 GET /api/book/1 请求之前调用 getBookDetails 函数。
    • 没有,你可以在getBookDetails开头写console.log(bookId),应该打印1
    • 这快把我逼疯了,是时候回去从头学东西了。使用回调会导致函数太多。使用 Promise 意味着我必须再次学习新的东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    • 2017-06-30
    • 2019-11-25
    • 2021-08-21
    • 1970-01-01
    相关资源
    最近更新 更多