Node.js的等待回调或数据库的响应
我已经看到了很多非常类似的问题,但不给予直接的答案其实等待。我有一个基于Bookshelf.js的脚本;Node.js的等待回调或数据库的响应
var Product = bookshelf.Model.extend({
tableName: 'amazon_products',
hasTimestamps: true,
virtuals: { //https://github.com/bookshelf/bookshelf/wiki/Plugin:-Virtuals
hasSiteProduct: function() {
var product_references = this.related('siteProductsReferences').fetch()
return product_references.length;
}
}
});
我已经建立了虚拟财产,将简单地计算模型的一对多关系,并返回计数。但在这种情况下,看起来this.related('siteProductsReferences').fetch()
在返回响应之前需要一段时间。 this.related('siteProductsReferences').fetch()
也有一个承诺,看起来像这样;
this.related('siteProductsReferences').fetch().then(function(result) {
// ...
});
我正在构建这个通过API返回。如果我只是将return this.related('siteProductsReferences').fetch()
添加到方法中,我将获得完整的方法;
,"hasSiteProduct":{"isFulfilled":false,"isRejected":false}
很明显,回调尚未完成。
因为数据库操作返回一个承诺,你的函数也需要返回一个承诺 - 没有摆脱,你必须将承诺传递给调用者,这将需要.then()它。
下面不起作用,因为你不能访问尚未履行尚未承诺。长度:
hasSiteProduct: function() {
var product_references = this.related('siteProductsReferences').fetch()
return product_references.length;
}
但是你可以这样做:
hasSiteProduct: function() {
var product_references_length_promise =
this.related('siteProductsReferences').fetch()
.then(product_references => {
return product_references.length;
})
// return the promise - it has not completed yet, client must .then() it
return product_references_length_promise;
}
客户需要。然后()诺言如此回复:
hasSiteProduct().then(num_product_references => {
// do something with num_product_references
})
为什么它的价值我想你可能会走下去构建数据的内存模型时出现错误的路径。这已经与数据库中的数据处理时由面向对象的开发人员青睐的技术,但我总是发现很难使一个优雅的方式这项工作 - 它需要努力构建模型有很多这样的努力没有按”真的还清。
谢谢这是我正在寻找的解释。 – LogicDev
可能是[如何从异步调用返回响应]的副本(https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call )。 – jfriend00
'this.related( 'siteProductsReferences')。取()'显然返回一个承诺。你可以在promise上使用'.then()'来注册一个回调函数,当它有一个值的时候会被调用。 – jfriend00
可能的重复[如何返回来自异步调用的响应?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – peteb