简体   繁体   English

如何保证 promise 永远不会拒绝的 API 用户

[英]How to guarantee an API user that a promise never rejects

I have a promise returning function and that promise never rejects I always handle all errors and still resolve a value.我有一个 promise 返回 function 并且 promise 从不拒绝我总是处理所有错误并仍然解决一个值。 I want to inform the user that s/he doesn't have to append catch function to the promise.我想通知用户,她/他不必将 append 捕获 function 到 promise。


const createItem = (name: string): Promise<boolean> => {
   return new Promise<boolean>(resolve => {
       someAjaxCall().then(response => {
           if (response.status >= 200 && response.status < 300) {
              resolve(true);
           } else {
              handleError();    // some logging to console
              resolve(false);
           }
       }).catch(error => {
           handleError();    // some logging to console
           resolve(false);
       });
   });
} 

Actually changing return type to Promise<void> and replacing resolve(true) parts with resolve() and replacing resolve(false) parts with reject() solves my problem.实际上将返回类型更改为Promise<void>并用resolve(true) resolve()替换 resolve(true) 部分并用reject()替换resolve(false)部分解决了我的问题。

But I want to know that is there any other elegant way to tell the API user that "you won't ever need to append catch and you must handle exactly these values in your then".但我想知道有没有其他优雅的方式告诉 API 用户“你永远不需要 append 捕获,你必须在你的 then 中准确处理这些值”。

But I want to know that is there any other elegant way to tell the API user that "you won't ever need to append catch and you must handle exactly these values in your then".但我想知道有没有其他优雅的方式告诉 API 用户“你永远不需要 append 捕获,你必须在你的 then 中准确处理这些值”。

No. Similar to the fact that there is no way in the type system to say a function never throws there is no way for promise never rejects .没有。类似于在类型系统中没有办法说function never throws没有办法promise never rejects

Your only option is to add documentation for this fact if you want如果需要,您唯一的选择是为此事实添加文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM