我几个小时前刚刚开始学习JavaScript和promise,我开始了解"流程",但有几个细节还不清楚。让我们看看下面的例子:
function OnRejected(var){
return console.log("This is an error " + var)
}
Promise.reject(2).then(function(a){return a*2})
.then(function(a){return a+5})
.then(function(a){return a*3})
.then(console.log)
.catch(OnRejected)
上面代码的结果:这是一个错误2
上面的例子工作得很好。我的问题是:如果我不调用函数,而是试图直接调用catch中的"console.log("这是一个错误")",为什么它会失败?像这样:
Promise.reject(3).then(function(a){return a*2})
.then(function(a){return a+5})
.then(function(a){return a*3})
.then(console.log)
.catch(console.log("This is an error"))
结果是:
(节点:39515)未处理的PromiseRejection警告:3
这是一个错误
。此错误源于在没有catch块的异步函数内部抛出,或拒绝未使用.catch()处理的promise。(拒绝id:2)
(节点:39515)[DEP0018]弃用警告:不赞成使用未处理的promet拒绝。将来,未处理的promise拒绝将使用非零退出代码终止Node.js进程
进程已完成,退出代码为0
除了"承诺"之外,我相信我对JS、console.log和console.log中的函数缺乏了解。任何帮助或建议都将不胜感激。
catch()
和then()
期望接收一个函数作为参数。在您的示例中,OnRejected
是一个函数,而console.log("This is an error")
不是。
更详细地解释一下:console.log
是一个函数,但console.log('something')
是用参数'something'
执行函数console.log
的结果。
要返回到catch()
和then()
,它们将调用您给它的方法(在您的示例中:OnRejected
),并使用先前解析的promise返回的任何内容作为参数来调用它。
示例:
getDataFromDistantServer().then(function (data) => {
console.log(data)
return otherCallToOtherServer()
}).then( function (dataFromOtherServer) => {
console.log(dataFromOtherServer)
})
这也会起作用,因为doSomething
是一个函数:
var doSomething = function(data) {
console.log(data)
return otherCallToOtherServer()
}
getDataFromDistantServer()
.then(doSomething)
.then( function (dataFromOtherServer) => {
console.log(dataFromOtherServer)
})
旁注:函数OnRejected
的命名约定要求名称不以大写字母开头,并称之为onRejected