![](/img/trans.png)
[英]Promise.all in JavaScript: How to get resolve value for all promises?
[英]JavaScript Promises - force promise to resolve
考虑到我有以下几点:
const timeoutPromise = new Promise(resolve => setTimeout(resolve("Failure"), 5000));
const response = await Promise.race([infinite_task, timeoutPromise]);
infinite_task
任务是一个 promise 永远不会解决或拒绝。 我尝试使用Promise.race
但它永远不会比较两个承诺,因为infinite_task
永远不会结束。
如何在超时后(在本例中为 5 秒后)强制解决infinite_task
任务?
您在setTimeout
function 中存在行为错误。 当您应该传递回调时,您正在传递resolve
function (即undefined
)的结果作为setTimeout
的参数。 这意味着您的timeoutPromise
实际上会立即解决,而不是在真正的超时之后。 这表现如你所料:
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));
为清楚起见,我按步骤分解您所做的:
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.