假设我有3个文件。如何处理Node.js中的回调?
index.js拨打电话时这样
$.post('/test/', data, function(response) {
//handle success here
})
routes.js后端处理这样
app.post('/test/', function(req, res){
item.getItems(function(response){
res.json(response);
});
});
items.js的路径是访问数据库,使一个模型每个项目的POST请求
function getItems(callback) {
database.query('SELECT * from items', function(result){
result.forEach(function(item){
request.post('/api/', item, function(req, res) {
//finished posting item
});
});
});
//callback here doesnt wait for calls to finish
}
其中/何时应该调用传递给getItems()的回调以处理index.js中的成功/失败?
@JackJohnson - 为你做了这项工作? – jfriend00
我还没有试过,明天我会试试看第一件事。谢谢。 –
@ jfriend00,我很想知道'诺言'。map'排成一行** //错误在这里** getItems'的一部分...让我们假设你有20个项目用于'postAsync',其中15个成功,5个失败......将15个结果放在'results'中为了成功和5在错误中的错误?我对承诺有什么高层次的理解,但我还没有看到一个承诺数组的例子。 – incutonez