我不明白下面的部分
var q = require("q"),
BlogPost = require("../models/blogPost");
module.exports = {
getAllPosts: getAllPosts
};
function getAllPosts() {
var deferred = q.defer();
BlogPost
.find({})
.sort("-date")
.exec(function(error, posts) {
if (error) {
deferred.reject(error);
} else {
deferred.resolve(posts);
}
});
return deferred.promise;
}我在控制器中找到了上面的代码,但我不能理解它。为什么在最后我们使用return deferred.promise?稍后我将如何使用getAllPosts?难道我们不能只返回posts对象吗?
发布于 2016-09-05 10:33:54
您可以使用一个函数返回一个promise,如下所示:
var getAllPosts = require('./your-module-name.js').getAllPosts;
getAllPosts()
.then(function(posts) {
//successfully process the posts
})
.catch(function(err) {
//handle the error
})
.finally(function(){
//clean up anything you need to...
})发布于 2016-09-05 10:15:43
Promise是异步结果的正确表示。
它有三种状态:
1->成功
->错误
->挂起
deferred是一个正确的promise对象,它在处理上述状态之一后返回。
我们可以在没有承诺的情况下使用javascript代码,但有时我们必须提供它才能使我们的代码成为execute as asynchronous way。
这就是我们使用promise的原因
https://stackoverflow.com/questions/39323058
复制相似问题