我很难在下面看到承诺拒绝的地方:
MongoClient.connect(mongourl)
.then(db => {
console.log("making promises:", typeof lib.getAllData)
// let promises = packages.map(repo => lib.getAllData(db, repo));
let promises = [];
console.log("making promises2")
// return getAllData(db, packages[0])
return Promise.all(promises)
.then(results => {
console.log("RAW RES", results);
let missing = results.filter(r => r.error).map(r => r.error)
return (db, missing);
})
// Should never fail as getAllData always resolves
.catch(err => {
console.log("err1", err);
return Promise.reject({db, err})
});
}).then(({db, results}) => {
console.log("RES: ", results);
db.close();
}).catch(({db, err}) => {
console.log("Final Err:", err);
db.close();
});
我在控制台中看到的是
making promises: function
making promises2
RAW RES []
RES: undefined
Final Err: undefined
(node:7026) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'close' of undefined
(node:7026) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
我有两个问题:
undefined
- 我希望它是[]
答案 0 :(得分:1)
我没有完成整个代码但是从一眼就看出来我觉得你的deconstructing已经破了:
const test = () => {
return ('one','two');
}
console.log( test() )
将按照您的建议返回two
,而不是{'one', 'two'}
。
所以改变你的代码:
MongoClient.connect(mongourl)
.then(db => {
console.log("making promises:", typeof lib.getAllData)
// let promises = packages.map(repo => lib.getAllData(db, repo));
let promises = [];
console.log("making promises2")
// return getAllData(db, packages[0])
return Promise.all(promises)
.then(results => {
console.log("RAW RES", results);
let missing = results.filter(r => r.error).map(r => r.error)
return {db, missing};
// ^------- THE CHANGE
})
// Should never fail as getAllData always resolves
.catch(err => {
console.log("err1", err);
return Promise.reject({db, err})
});
}).then(({db, results}) => {
console.log("RES: ", results);
db.close();
}).catch(({db, err}) => {
console.log("Final Err:", err);
db.close();
});
我还建议抽象这些函数,以便获得一个很好的承诺链。
为什么RES未定义 - 我希望它是[]
你返回一个变量而不是一个对象,所以db
和results
都是undefined
为什么我最终会在最后的错误"因为在这个脚本中不应该出现拒绝
着名的遗言;) 总是假设事情会破裂。
答案 1 :(得分:0)
所以错误就是我回来了 - 正如多米尼克所说:
return (db, missing);
应该是
return {db, missing};
但是在我的.then
我是
{db, results}
并且无法找到结果,因为我返回了一个名为missing