简体   繁体   English

JavaScript 承诺 - 强制 promise 解决

[英]JavaScript Promises - force promise to resolve

Considering that I have the following:考虑到我有以下几点:

const timeoutPromise = new Promise(resolve => setTimeout(resolve("Failure"), 5000));

const response = await Promise.race([infinite_task, timeoutPromise]);

The infinite_task is a promise that never resolves or rejects. infinite_task任务是一个 promise 永远不会解决或拒绝。 I tried to use Promise.race but it will never compare both promises, since infinite_task never ends.我尝试使用Promise.race但它永远不会比较两个承诺,因为infinite_task永远不会结束。

How can I force infinite_task to resolve after a timeout (in this case, after 5 seconds)?如何在超时后(在本例中为 5 秒后)强制解决infinite_task任务?

You have a behavioural error in the setTimeout function.您在setTimeout function 中存在行为错误。 You are passing the result of the resolve function (that is undefined ) as parameter of the setTimeout , when you should pass a callback.当您应该传递回调时,您正在传递resolve function (即undefined )的结果作为setTimeout的参数。 This means that your timeoutPromise actually resolves instantly and not after the real timeout.这意味着您的timeoutPromise实际上会立即解决,而不是在真正的超时之后。 This behaves as you expect:这表现如你所料:

 let infinite_task = new Promise(() => { /* never resolving promise */ }); const timeoutPromise = new Promise(resolve => { setTimeout(() => { // this is the needed change to the callback resolve("Failure") }, 5000) }); const response = Promise.race([ infinite_task, timeoutPromise ]).then(e => console.log('Result:', e)); // making it a function function awaitFor(promise, millis) { return Promise.race([ promise, new Promise((resolve, reject) => { // NOTE: here better to use reject so we can use catch to see if // the promise was fulfilled or timeout was elasped setTimeout(() => reject('timeout'), millis) }) ]); } awaitFor(infinite_task, 10000).then(() => console.log('infinite task was not so infinite.')).catch(e => console:log('Error2,'; e));

Decomposing your code:分解你的代码:

For clarity I decompose in steps what you did:为清楚起见,我按步骤分解您所做的:

const timeoutPromise = new Promise(resolve => setTimeout(resolve("Failure"), 5000));

// Promise function dec.
const timeoutPromise = new Promise(function(resolve) {
    setTimeout(resolve("Failure"), 5000)
});

// setTimeout arguments dec.
const timeoutPromise = new Promise(resolve => {
    let timeout = 5000;
    let callback = resolve("Failure") // this fulfill the promise and returns undefined
    setTimeout(callback, timeout);
});

// variable-values substitutions
const timeoutPromise = new Promise(resolve => {
    resolve("Failure") // this fulfill the promise and returns undefined
    setTimeout(undefined, 5000); // this pratically do nothing
});

// contraction (actual code executed, at the end of the day)
const timeoutPromise = new Promise(resolve => resolve("Failure"));

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

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