如何从内部拒绝承诺然后起作用 [英] How to reject a promise from inside then function

查看:52
本文介绍了如何从内部拒绝承诺然后起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的问题,但是在诺言链中间,您如何从then函数之一内部拒绝诺言呢?例如:

This is probably a silly question, but mid promise chain, how do you reject a promise from inside one of the then functions? For example:

someActionThatReturnsAPromise()
    .then(function(resource) {
        return modifyResource(resource)
    })
    .then(function(modifiedResource) {
        if (!isValid(modifiedResource)) {
            var validationError = getValidationError(modifiedResource);
            // fail promise with validationError
        }
    })
    .catch(function() {
        // oh noes
    });

不再有对原始解析/拒绝函数或PromiseResolver的引用.我只是应该添加 return Promise.reject(validationError); 吗?

There's no longer a reference to the original resolve/reject function or the PromiseResolver. Am I just supposed to add return Promise.reject(validationError); ?

推荐答案

我只是应该添加 return Promise.reject(validationError); ?

是的.但是,它是如此复杂,仅在jQuery中,并带有 Promise/A + 兼容的库,您也可以简单地

Yes. However, it's that complicated only in jQuery, with a Promise/A+-compliant library you also could simply

throw validationError;

因此您的代码将如下所示

So your code would then look like

someActionThatReturnsAPromise()
    .then(modifyResource)
    .then(function(modifiedResource) {
        if (!isValid(modifiedResource))
            throw getValidationError(modifiedResource);
        // else !
        return modifiedResource;
    })
    .catch(function() {
        // oh noes
    });

这篇关于如何从内部拒绝承诺然后起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆