挑戰說明
嘗試實作包含帶有 setTimeout 和 promise 的遞回函式的片段的嘗試不成功。遞回和 setTimeout 有效,但承諾似乎沒有得到解決,因為在 projectMGR() 中配置的thenable中沒有訊息輸出。
解決方案嘗試
對執行背景關系的廣泛審查、promise 解決的各種方法、MDN 上的練習以及堆疊溢位解決方案的審查都被證明是不成功的。此外,已經嘗試將遞回函式的呼叫包裝在異步中(如當前配置的那樣),還直接在 GEC 中配置承諾。
堆疊溢位參考
解決方案 1 解決方案 2 解決方案 3
非常感謝任何意見或幫助。
| 預期產出 | 實際輸出 |
|---|---|
| 還有10個... | 還有10個... |
| 還有9個... | 還有9個... |
| 還有8個... | 還有8個... |
| 還有7個... | 還有7個... |
| 還有6個... | 還有6個... |
| 還有5個去... | 還有5個去... |
| 還有4個... | 還有4個.. |
| 還有3個... | 還有3個... |
| 還有2個去... | 還有2個去... |
| 還有1個去... | 還有1個去... |
| 正好趕上歡樂時光!??。 |
projectMGR();
const prom = [];
async function recursiveInterval(arr, n, ms = 1000) {
return new Promise((resolve) => {
setTimeout (() =>
{
if (n === 0) {
resolve(`Finished just in time for Happy Hour!??. `)
} else {
console.log(`${n} more to go...`);
recursiveInterval(arr, n - 1) - arr[n - 1];
};
},ms);
}
);
};
async function projectMGR() {
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let n = arr.length;
new Promise(() => {
recursiveInterval(arr, n)
.then((resolve) => console.log(resolve))
})
}
uj5u.com熱心網友回復:
這效果更好。并且始終記住在定義它們之后使用函式或變數。
async function recursiveInterval(arr, n, ms = 1000) {
if (n === 0) {
return 'Finished just in time for Happy Hour!??.';
} else {
console.log(`${n} more to go...`);
await new Promise(res => { setTimeout(res, ms); });
const t = await recursiveInterval(arr, n - 1);
return t;
}
};
async function projectMGR() {
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let n = arr.length;
await recursiveInterval(arr, n)
.then((resolve) => console.log(resolve))
}
projectMGR();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/532417.html
標籤:javascript递归
上一篇:有沒有辦法將函式存盤在向量中?
