[英]What is the meaning of 'catch(…)' with no '{…}' block following it?
我在一些npm
包中看到一段類似於下面的代碼:
this.func(callback).then(function() {
...
return x;
}).then(function() {
...
return y;
}).then(function() {
...
return z;
}).then(function() {
mocha.run(function(failures) {
...
callback(failures);
});
}).catch(callback);
問題:
這個catch(callback)
后面沒有{...}
塊是什么意思?
我想添加一個finally
子句來執行callback
,但我嘗試的每個語法似乎都失敗了:
.catch(callback).finally(callback);
.catch(callback).finally(callback());
.catch(callback).finally{callback()};
.catch(callback).finally(){callback()};
在您的情況下, then 和 catch 指的是 Promise 的原型,而不是本機 catch 實現。 檢查這個例子以更好地理解它:
let doSomething = () {
return new Promise((resolve, reject) => {
try {
reject();
} catch(e) {
reject();
} finally {
console.log('done');
}
});
}
doSomething().then(() => {}).catch(() => {});
請注意,無論您做什么,都會調用 catch。
在您的情況下, catch
函數是指您在catch
塊中傳遞的callback
函數
//first case
function callback(){}
catch(callback);
//second case
catch(function(){})
兩種情況都會起作用
finally
它仍然缺乏瀏覽器支持,您可以在此頁面底部查看
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally
並檢查this以了解如何finally
以替代方式進行。
你可以這樣試試。 有關承諾的更多詳細信息: 請參閱此處
doSomething(()=>{//do something})
.then(()=>{})
.catch((error)=> { console.log(error); })
.finally(()=> { //finally block here });
問題 1: Promise API 會在Promise被“ 拒絕”時調用catch
傳遞的函數。 因此,請考慮以下代碼:
// method 1: define the callback function
var callback = function(error){
console.error(error); // console the error
};
this.func.then(...).catch(callback);
// method 2: pass the function assigned to "callback" variable itself
this.func.then(...).catch(function(error){
console.error(error); // console the error
});
您只是告訴上面(在您的代碼中)函數調用返回的承諾:“嘿,每當您未能完成任務時,請調用我(或其他人)定義的這個函數callback
。”
問題 2:您的四種方法列表中的第一種方法應該有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.