【发布时间】:2015-07-18 10:37:10
【问题描述】:
我是 node 新手,我正在尝试找出回调及其异步性质。
我有这种功能:
myObj.exampleMethod = function(req, query, profile, next) {
// sequential instructions
var greetings = "hello";
var profile = {};
var options = {
headers: {
'Content-Type': 'application/json',
},
host: 'api.github.com',
path: '/user/profile'
json: true
};
// async block
https.get(options, function(res) {
res.on('data', function(d) {
// just an example
profile.emails = [
{value: d[0].email }
];
});
}).on('error', function(e) {
console.error(e);
});
//sync operations that needs the result of the https call above
profile['who'] = "that's me"
// I should't save the profile until the async block is done
save(profile);
}
鉴于大多数节点开发人员都使用此解决方案或类似解决方案,我还试图了解如何使用 Async library。
如何“阻止”(或等待结果)我的脚本流程,直到我从 http 请求中获得结果?可能以异步库为例
谢谢
【问题讨论】:
-
不,我不这么认为。我的范围在节点中,我想查看此用例中异步库的示例用法
-
"block[ing]" javascript,直到结果返回完全不利于编写异步代码。您需要在异步操作的回调函数中运行您想要在异步操作之后运行的代码。这就是回调函数的全部意义所在。链接的副本很好地解释了这一点。 (下面的答案涵盖了您的特定用例,尽管您实际上并不需要异步库。)
标签: javascript node.js asynchronous node-async