【发布时间】:2018-09-25 23:21:43
【问题描述】:
我有以下我无法弄清楚的问题。这是我的代码:
//file1.js
module.exports = {
delete: function(id) {
return new Promise((resolve,reject) => {
setTimeout(() => {reject('bla bla');}, 2000);
});
}
}
//file2.js
const file1 = require('file1');
var delPr = file1.delete(id);
delPr.then(() => {
console.log('+++++++++++++++++++++++++++');
res.status(200).json({
message : "delete post"
});});
delPr.catch((error) => {
console.log('-----------------------------');
}
当这是我得到的代码时:
-----------------------------
(node:102437) UnhandledPromiseRejectionWarning: bla bla
(node:102437) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:102437) [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.
将 file2.js 中的代码更改为:
file1.delete(id).then(() => {
console.log('+++++++++++++++++++++++++++');
res.status(200).json({
message : "delete post"
});}).catch((error) => {
console.log('-----------------------------');
});
});
一切正常,我只在控制台中得到'--------',有人可以解释一下有什么区别吗?我没有看到一个,我在过去的 3 个小时里一直在看它。
【问题讨论】:
-
delPr.then(…)的返回值与delPr不一样 -
你能详细说明吗???你说
then子句被击中了,那为什么我看不到++++打印??? -
我并不是说调用了实现回调。我说
.then()方法调用本身返回的不是delPr,这就是你没有看到的区别 -
.then()仅在执行时调用,还是我错了? -
所有这些,在某个时候。您可能想阅读文档,了解在哪些情况下
then/catch返回的承诺会被履行/拒绝。
标签: javascript node.js error-handling