我試圖理解為什么我在以下代碼后出現計算器溢位錯誤:
const promise = new Promise((res,rej) => {
res(4);
})
while(true){
promise.then((v) => v)
}
我期待得到
4
4
4
4
.
.
.
但得到:
FATAL ERROR: MarkCompactCollector: semi-space copy, fallback in old gen Allocation failed - JavaScript heap out of memory
uj5u.com熱心網友回復:
我將說明您如何創建一個沒有這個問題的無限系列承諾,但警告:您的選項卡將被卡住:
const pr = new Promise((res,rej) => {
res(4);
});
(async () => {
let promiseList = [];
while(true){
const p = pr.then((v) => console.log(v));
promiseList.push(p);
if (promiseList.length >= 20) {
await Promise.all(promiseList);
promiseList = [];
}
}
})();
檢查您的控制臺,您會看到 4s。
uj5u.com熱心網友回復:
嘗試在異步函式內部使用回圈,如下所示
async function someFunction(){
while(true) {
console.log(await promise);
}
}
someFunction();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/341342.html
標籤:javascript 承诺
下一篇:合并和洗掉嵌套陣列中的元素
