2017-08-05 62 views
-1

我是一名PHP开发人员,目前我正在开发一个node.js项目,之前我从未体验过异步,所以它让我困惑。如何做好异步?

我真的必须这样做吗?

// user model 
exports.getRandomUser = function(cb){ 
    db.query('...query...', cb); 
} 
// post model 
exports.getRandomPost = function(uid, cb){ 
    db.query('...query...', cb); 
} 
// router 
router.get('/', function(req, res) { 
    user.getRandomUser(function(userInfo){ 
     post.getRandomPost(userInfo.id, function(postInfo){ 
      res.render('post', {data: postInfo}); 
     }); 
    }); 
}); 

有什么办法可以让它更容易混淆?

回答

0

伟大的问题,是的有一个更简化的方式。你在做什么这里是回调后的回调,这使得代码看起来“混乱”

通常所说回调地狱

它看起来很漂亮,现在的标准,但在时间它会成长为一个饥饿编程权力的野兽,一直需要你的关注。

对于JavaScript专业版来说,处理它并不是很难,但是如果你想在接近回调时拥有更轻松的风格,您可以使用承诺。承诺是迈向未来的JS,但我认为这是很好的了解BOTH

回调主要有两个参数,它看起来像这样:

dothis(function (error, data) { 
    if (error) { 
      throw new Error(error) 
    } 

    console.log('we have data', data) 
}) 

有了承诺,这变得更加容易在语义方面

dothis.then(function(data) { 
    console.log('we have data', data) 
}).catch(function(error) { 
    throw new Error(error) 
}) 

这当然只是如果你的功能兼容的承诺,如果你想了解更多有关承诺,请查看本教程的github努力了解:https://github.com/then/promise

你甚至可以链接承诺,并创建一个非常干净的代码库!