簡體   English   中英

JavaScript 承諾 - 強制 promise 解決

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM