我一直遇到有關 JS promise 使用的問題,希望這只是我遺漏了一些非常明顯的東西。本質上,我嘗試一次讀取多個 JSON 文件并將它們的內容推送到屬于另一個對象的數組,然后對該數組上的元素執行操作。因此,在嘗試對其進行操作之前需要填充數組。然而,盡管我在理論上使用 promises 來確保順序是正確的,但我所寫的似乎無法做到這一點。我該如何解決這個問題?以下是我正在使用的代碼片段,其中出現了問題:這是我將提取的對象推送到我的數組的函數:function pushNewRoom (ship, name_json_folder, elem, id) { lt promiseRoom = new Promise ((resolve, reject) => { let newRoom = gf.getJSONFile(name_json_folder + '/' + elem + ".json") // note: getJSONFile allows me to grab a JSON object from a file .then( (data) => { data.name = elem; ship.rooms.push(data); return data; }).then((newRoom) => { resolve(newRoom); }).catch((reject) => { // if the JSON file doesn't exist a default object is generated let newRoom = new Room (elem, id); ship.rooms.push(newRoom); resolve(newRoom); }); }); return promiseRoom;}這是調用該函數并執行我之后需要的操作的部分:exports.generateRoomsByLayout = function (name_json_folder, ship){ ship.rooms = []; console.log("reached step 1"); // First execution step: get a JSON file gf.getJSONFile(name_json_folder + "/_base_layout.json") .then(function (shipmode){ // Note: shipmode is a JSON object that acts as a blueprint for the operations to follow. // Importantly here, it contains an array, layout, containing the names of every other JSON file I will need to perform the operations. console.log("reached step 2"); }).catch((err) => { }); });};這個問題就發生在 Promise.allSettled() 行。程序沒有等待 ship.layout.map() 生成的 promise,它會變成一個可迭代的數組,而是繼續執行。我想這是因為 Promise.allSettled() 沒有等待 map() 生成數組才繼續前進,但一直無法解決問題,并且仍然懷疑這是解釋。誰能告訴我我在這里做錯了什么?如果我問的不清楚,請告訴我,我會盡力澄清。編輯:我懷疑它鏈接到 Promise.allSettled() 而不是等到 map() 填充數組以考慮數組內的每個承諾都已解決,因為它的長度在第 3 步似乎為 0,但我不確定。
JS - 在繼續下一部分之前未能正確解決一系列承諾
肥皂起泡泡
2022-12-29 16:18:30