【发布时间】:2020-06-12 05:42:50
【问题描述】:
所以,在使用 Promise 方面,我并不是很新。我了解并且之前使用过.then(), .catch(), Promise.all()。我主要用它们来获取 API 调用。
但是,在创建自己的承诺方面,我是一个完全的初学者。
所以,我试图创建自己的承诺,reject() 函数不断给我unhandled error (my rejection message) 消息。虽然,resolve() 函数按预期工作。
这是我的(简化)代码:
const request = require('request-promise');
return new Promise(async (resolve, reject) => {
try {
/*
* Some other codes that might throw other exceptions
*/
....
....
const options = "ASSUME THIS IS A CALL TO A THIRD-PARTY API";
await request(options)
.then((val: any) => {
...
// I had no issue with this. Resolve returns properly
resolve(val);
})
.catch((e: any) => {
...
// I would need to translate the error message from this
// Third-Party API. But, this reject function keeps on
// returning me an "unhandled error" issue
reject(translateMsg(e.message, "fr"));
});
}
catch(err) {
reject("Oops other errors detected");
}
}
注意:此错误消息显示在我的 Firebase 函数日志中。我不确定问题出在我的代码还是其他地方。
谢谢!
(编辑 1)
我在request.catch() 语句中做了一些其他的处理(翻译等)。所以,我需要返回一个新的错误消息,而不是默认的 e 对象。
(编辑 2)
假设translateMsg() 已经过良好测试并且它总是返回一个字符串。
【问题讨论】:
-
这里
request已经返回了一个承诺。你为什么要在另一个 Promise 上创建 Promise? -
无论使用什么你创建的这个承诺显然都不能处理拒绝......?
-
@palaѕн 实际上,为了简洁起见,我没有在此处粘贴一些代码。所以,
request.then()和request.catch()中还有一些其他的代码。我试图处理请求的结果并返回一个新的 Promise -
@deceze 我将这个 npm 包 (npmjs.com/package/request-promise) 用于
request(),根据文档,它确实可以处理拒绝。
标签: javascript typescript promise