在nodejs中,很多函数调用都是作为非阻塞函数实现的。有时这些函数调用之间可能存在依赖关系。例如,当用户登录时,我想首先获取用户的用户类型,然后根据用户类型我可以获取刚刚分配给该用户类型的任务。在非阻塞函数中,我使用嵌套函数调用:
$http.post(url_login, login_request)
.success(function(req) {
$http.post(url_get_tasks, req.type)
.success(function(req) {
//update tasks
})
})
许多库仅提供非阻塞功能,例如node_redis库。有没有什么好的方法可以处理嵌套的非阻塞函数调用来解决依赖问题。
最佳答案
有一个页面专门解决这个问题:http://callbackhell.com/
总而言之,您可以选择
- 使用命名函数,as codebox suggests
- 使用async图书馆
- 或使用 promise
如果我没记错的话,
您正在使用 Angular $http
服务,它应该支持正确的
promise 链接,因此您可以将代码减少到
$http.post(url_login, login_request)
.then(function(req){
return $http.pos(url_get_tasks, req.type);
})
.then(function(req){
// update tasks
})
.catch(function(err){
// errors from the first AND second call land here
})
您可以为异步函数编写一个简单的包装器,将它们变成 promise :
// this assumes standard node.js callbacks with the
// signature (error, data)
function toPromise(fn){
return function() {
var args = Array.prototype.slice.call(arguments);
var scope = this;
return new Promise(function(resolve, reject){
var cb = function(err, data) {
return err ? reject(err) : resolve(data);
};
args.push(cb);
fn.apply(scope, args);
});
};
}
// turn fs.readdir into a promise
var readdir = toPromise(require('fs').readdir);
readdir('.')
.then(function(files){
console.log(files);
})
.catch(function(err){
console.log('reading files failed');
})
还有另一个关于 Angular $http
promise 的问题,这可能会帮助您更好地理解它们:here
关于javascript - 解决 Node 中非阻塞函数调用的依赖关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26801772/