gpt4 book ai didi

javascript - 如何拒绝我没有创建的 promise ?

转载 作者:行者123 更新时间:2023-11-29 16:47:35 24 4
gpt4 key购买 nike

这里的 promise 还很陌生,我想知道..

在查看用于处理 promise 的 bluebird 包之后:

  • 创建解析器
  • 解决成功/拒绝失败
  • 返回创建的解析器 promise 属性

我一直想知道如何使用已经创建 promise 的包来实现拒绝 promise 以引发 catch 的相同效果,而我只是使用它们的 .then 链?

我的意思是,在我的创建解析器上使用 reject 最终会向此函数的用户引发一个 catch

如果我没有解析器,我如何引发一个catch。如下链接 promise :

function doSomthing(): Promise<someValue>
return somePackage.someMethodWithPromise().then((result)=> {
return someValueToTheNextThen;
})
}

我看到一些包实现它的唯一方法是返回一个 { errors, result } 对象,以便下一个 then 可以检查是否有任何错误并对它使用react,但我想提出一个 catch 而不是检查我拥有的每个 then 中的错误..

希望我说清楚了,如果有任何遗漏,请告诉我。

在此先感谢您的帮助!

最佳答案

就像在同步代码中一样,您可以通过抛出错误来实现这一点。当您使用 promises 并且已经在 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);
});

关于javascript - 如何拒绝我没有创建的 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39689919/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com