嵌套的promise节点js
nested promises node js
我从这里读了教程,我不明白为什么第二个"insertOne"不起作用。谢谢你的帮助!
var Promise=require('promise');
var MongoClient=require('mongodb').MongoClient;
var url = 'mongodb://localhost/EmployeeDB';
MongoClient.connect(url)
.then(function(db)
{
db.collection('Documents').insertOne({
Employeeid: 1,
Employee_Name: "Petro"})
.then(function(db1) {
db1.collection('Documents').insertOne({
Employeeid: 2,
Employee_Name: "Petra"})
})
db.close();
});
您有两个异步操作(db.insertOne)正在发生。
因此,您应该在第二次插入后有一个.then
并关闭连接
代码应该看起来像这个
{
db.collection('Documents').insertOne({
Employeeid: 1,
Employee_Name: "Petro"})
.then(function(db1) {
db1.collection('Documents').insertOne({
Employeeid: 2,
Employee_Name: "Petra"})
}).then(function(db2) {
db.close();
})
});
参见评论
MongoClient.connect(url)
.then(function(db) {
// you need a return statement here
return db.collection('Documents').insertOne({
Employeeid: 1,
Employee_Name: "Petro"
})
.then(function(record) {
// another return statement
// try db instead of db1
return db.collection('Documents').insertOne({
Employeeid: 2,
Employee_Name: "Petra"
})
})
.then(function() {
// move the close here
db.close();
})
})
// Add an error handler
.then(null, function(error){
console.log(error)
})
相关文章:
- 如何处理node.js节点mongodb中的连接和查询队列
- 更新从Mysql查询检索到的数据?Node.js节点mysql
- Dracula Graph js节点点击事件
- 如何公开JS节点模块
- Vis.js节点上的动画牛眼
- 添加“;三角形向上”;在d3.js节点中
- 验证请求参数的最佳方法是帆.js/节点.js
- 如何在新窗口中打开 Arbor.js 节点链接
- D3.js节点映射中的缩放功能
- 如何围绕焦点旋转 d3.js 节点
- 问.js节点承诺.“套接字”上缺少错误处理程序.类型错误:无法调用未定义的方法“then”
- 将数据返回到索引.js节点表达式
- 如何添加属性以 go.js 节点和重定向
- Js 节点 - socket.io 聊天修饰符
- 如何使用 JSON 图像作为 D3.js 节点背景
- 条件语句在 JS(节点)中没有响应
- Sigma JS节点动画
- 更改d3.js节点的填充颜色
- Arbor Js-节点单击
- 循环中的JS节点