[英]How to reject a promise i did not create?
這里的承諾還真是新奇,我很納悶。
在查看用於實現諾言的bluebird
軟件包后:
promise
屬性 我一直在想,我怎么能拒絕實現承諾提出一個相同的效果catch
使用已經創建的承諾包,而我只是用自己的.then
鏈?
我的意思是,用reject
我創建解析器最終會提出一個catch
到這一功能的用戶。
我怎樣才能養catch
如果我沒有解析器。 鏈接諾言如下:
function doSomthing(): Promise<someValue>
return somePackage.someMethodWithPromise().then((result)=> {
return someValueToTheNextThen;
})
}
只有這樣,我已經看到了一些包實現這一目標是通過返回{ errors, result }
對象,以便在未來then
可以檢查是否有任何錯誤,並作出反應,但我想提出一個catch
,而不是檢查錯誤在每一個then
我有..
希望我能說清楚,請讓我知道是否有任何遺漏。
先謝謝您的幫助!
就像在同步代碼中一樣,您可以通過引發錯誤來實現。 當您使用諾言並且已經在then
鏈中時,這是慣用法:
function doSomething(): Promise<someValue>
return somePackage.someMethodWithPromise().then((result)=> {
if (badResult(result)) {
throw new Error('Bad result!');
}
return someValueToTheNextThen;
})
}
doSomething()
.then(result => {
// this will get skipped if an error was thrown
})
.catch(error => {
// error will be caught here if one was thrown
console.error(error);
});
.then
也會返回一個Promise。 您可以簡單地創建一個被拒絕的承諾,如果確定有錯誤則從那里返回。
return somePackage.someMethodWithPromise().then(result => {
if (result.erroneous()) return Promise.reject('erroneous data');
return someValueToTheNextThen;
})
您也可以簡單地throw anError;
then
也將被catch
在catch
塊中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.