Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/442.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 通过传递承诺而拒绝承诺_Javascript_Promise_Es6 Promise - Fatal编程技术网

Javascript 通过传递承诺而拒绝承诺

Javascript 通过传递承诺而拒绝承诺,javascript,promise,es6-promise,Javascript,Promise,Es6 Promise,为什么aresolveing承诺正确地等待someOtherPromise完成,而reject没有完成?运行以下代码示例并检查console.log输出。我希望“myFailingPromise rejected”消息会在2000毫秒后显示,就像“myPromise resolved”一样 让其他人承诺=(以前的承诺)=>{ 返回新承诺((解决、拒绝)=>{ 设置超时(()=>{ console.log(在2000ms之后,previousPromise+'=>someOtherPromise

为什么a
resolve
ing承诺正确地等待
someOtherPromise
完成,而
reject
没有完成?运行以下代码示例并检查console.log输出。我希望“myFailingPromise rejected”消息会在2000毫秒后显示,就像“myPromise resolved”一样

让其他人承诺=(以前的承诺)=>{
返回新承诺((解决、拒绝)=>{
设置超时(()=>{
console.log(在2000ms之后,previousPromise+'=>someOtherPromise');
决定(“其他承诺”);
}, 2000);
});
}
让我的承诺=()=>{
返回新承诺((解决、拒绝)=>{
解决(其他承诺(“我的承诺”);
});
};
让我的失败承诺=()=>{
返回新承诺((解决、拒绝)=>{
拒绝(其他承诺(“我的失败承诺”);
});
};
myPromise()。然后((val)=>{
//这是在'someOtherPromise'解决后执行的。
console.log('myPromise resolved');
}).catch((错误)=>{
console.log(“拒绝我的承诺”);
});
myFailingPromise()。然后((val)=>{
//这是在'someOtherPromise'解决后执行的。
console.log(“myFailingPromise已解决”);
}).catch((错误)=>{
console.log(“myFailingPromise已拒绝”);

});解析承诺a时,如果解析承诺a时使用的值是承诺B,则承诺a将与承诺B的状态匹配

然而,当你拒绝一个承诺时,你只需要给出一个理由,不管这个理由看起来是否像一个承诺都无关紧要

在这两种情况下,您需要做的是使用
someOtherPromise
解决问题

如果您想等待第一个承诺并拒绝,您可以这样做:

let myFailingPromise = () => {
  return new Promise((resolve, reject) => {
    someOtherPromise.then(reject);
  });
};

拒绝只接受一个
原因
,以突出显示错误。别再承诺了。您可以用相同类型的另一个承诺来解决一个承诺,但您只能看到最后一个承诺的成功案例

请看一下这个经过调整的实现:

const someOtherPromise = new Promise((resolve, _) => {
    resolve("I am a success");
});
const failingPromise = new Promise((_, reject) => {
    reject("I failed for a reason");
});

someOtherPromise
    .then((result) => {
            console.log("some other promise resolves", result);
            failingPromise
                .then((success) => {
                    console.log("never called");
                })
                .catch((reason) => {
                    console.error("failing promise rejects", reason);
                });
        }
    )
    .catch((error) => {
        console.error("also never called", error);
    });
这是一种能够等待其他承诺导致回调地狱的方法。这就是为什么您还可以使用异步/等待语法:

const app = async () => {
        try {
            const success1 = await someOtherPromise; // will succeed
            console.log(success1);
            const success2 = await failingPromise; // never succceds
            console.log(success2); // never be reached
        } catch (e) {
            return Promise.reject(e); // catches the error of failing promise and rethrows it, redundant but here showcases error handling
        }
    }
;

app()
    .then(() => {
        console.log("never be reached because of failing promise");
    })
    .catch(console.error);

关于您更新的超时问题,以下是您可以做的事情,以便始终等待另一个承诺:

const otherPromise = async (willBeSuccesful: boolean) => {
    console.log("started timer for case", willBeSuccesful);

    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log("resolve timer for case", willBeSuccesful);

            const successValue = "Fnord"; // whatever you want

            return willBeSuccesful
                ? resolve(successValue)
                : reject("this other promise failed because of reasons"); // only provide a reason, not another promise
        });
    };
};

const alwaysWaitForOtherPromiseThenRejectAnyway = async (otherPromise) => {
    try {
        const success = await otherPromise; // always waits 2 seconds, not matter
        console.log("other promises succeeded with value", success);
    } catch (e) {
        return Promise.reject(e); // passing through reason, redundant, only to showcase
    }

    return Promise.reject("reason why this promise failed"); // only happens after otherPromise was resolved, you could swallow that error and fail here or resolve here as well
};

const succeedingPromise = otherPromise(true);
const failingPromise = otherPromise(false);

alwaysWaitForOtherPromiseThenRejectAnyway(succeedingPromise)
    .catch((reason) => console.error(reason)); // fail after waiting for success of other promise

alwaysWaitForOtherPromiseThenRejectAnyway(failingPromise)
    .catch((reason) => console.error(reason)); // will fail as soon as otherPromise fails
在拒绝发生之前,它将始终等待超时。拒绝将有不同的原因。输出将是:

started timer for case true
started timer for case false
resolve timer for case true
resolve timer for case false
other promises succeeded with value Fnord
reason why this promise failed
this other promise failed because of reasons

这就是工作原理。(不幸的是)。您在myPromise中的新承诺会立即通过
someOtherPromise
解决。因此,
myPromise().then()
实际上只是
someOtherPromise
的成功处理程序。你想在这里实现什么?我用一个合适的样本更新了这个问题。当承诺支持一个以承诺为论据的拒绝时,是否存在固有的错误?我想知道为什么它不遵循
resolve
规范。您可以使用任何类型的
resolve
。它可以是一个字符串、数字、对象,也可以是一个承诺或一个承诺的集合——任何你认为是你承诺成功案例的东西。拒绝只处理一个原因,即字符串消息或
错误。拒绝不应该包含其他承诺。@如果
拒绝
确实吸收了承诺,那么它与
解决
有什么不同?(事实上,
拒绝
根本没有必要。我们只能使用
解决
,使用
解决(承诺.履行(价值))
解决(承诺.拒绝(原因))
来区分成功和错误案例。)我设想
解决(我的承诺)
将导致
然后()
catch
之后被调用(取决于
myPromise
结果),但是
reject(myPromise)
将导致
catch()之后被调用。请注意,在这两种情况下,都应该等待
myPromise
成功/失败
解决
当有
捕获
等待失败案例时,两种情况都不是正确的方法。如果我想用承诺来拒绝这个承诺,我必须打电话给另一个承诺。然后(拒绝)
(有效)。我的问题是:
为什么拒绝(其他承诺)
不是supported@Flame在您的问题中更新您的美国案例。这听起来像是个XY问题。为什么你想用另一个承诺(设计不支持)来拒绝一个承诺?@k0pernikus我只想拒绝一个等待通过的承诺兑现的承诺。如果答案是“设计不支持它”或“拒绝不应该包含承诺”,那么这并不能回答问题,因为你基本上是说“你不能,因为你不能”。
resolve(其他承诺)。然后(()=>抛出新错误(“拒绝”)
更新后的答案调用
then(拒绝())
但它应该是
然后(拒绝)
否则我相信它会立即执行