在 Node 中同步 http 请求
Sync http request in 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。
如何才能"block"(或等待结果)我的脚本流,直到我从 http 请求中获得结果?可能以异步库为例
谢谢
基于您正在尝试 "block" 脚本执行这一事实,我认为您对异步的工作原理没有牢牢掌握。你绝对应该阅读我建议的骗局,尤其是这个回复:
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);
}
]);
我是节点的新手,我正在尝试弄清楚回调及其异步性质。
我有这样的功能:
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。
如何才能"block"(或等待结果)我的脚本流,直到我从 http 请求中获得结果?可能以异步库为例
谢谢
基于您正在尝试 "block" 脚本执行这一事实,我认为您对异步的工作原理没有牢牢掌握。你绝对应该阅读我建议的骗局,尤其是这个回复:
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);
}
]);