我是节点新手,我试图弄清楚它的回调和异步性质。
我有这种功能:
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请求得到结果?可能使用异步库作为示例
由于
答案 0 :(得分:1)
基于您尝试阻止"阻止"你的脚本执行,我不认为你已经牢牢掌握了异步的工作原理。你绝对应该阅读我建议的欺骗行为,特别是这个回应:
How do I return the response from an asynchronous call?
更具体地回答您的问题:
async.waterfall([
function(callback) {
// async block
https.get(options, function(res) {
res.on('data', function(d) {
// just an example
profile.emails = [
{value: d[0].email }
];
callback(null);
});
}).on('error', function(e) {
throw e;
});
},
function(callback) {
// I should't save the profile until the async block is done
save(profile);
callback(null);
}
]);