我一直遇到有關(guān) JS promise 使用的問題,希望這只是我遺漏了一些非常明顯的東西。本質(zhì)上,我嘗試一次讀取多個(gè) JSON 文件并將它們的內(nèi)容推送到屬于另一個(gè)對(duì)象的數(shù)組,然后對(duì)該數(shù)組上的元素執(zhí)行操作。因此,在嘗試對(duì)其進(jìn)行操作之前需要填充數(shù)組。然而,盡管我在理論上使用 promises 來(lái)確保順序是正確的,但我所寫的似乎無(wú)法做到這一點(diǎn)。我該如何解決這個(gè)問題?以下是我正在使用的代碼片段,其中出現(xiàn)了問題:這是我將提取的對(duì)象推送到我的數(shù)組的函數(shù):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;}這是調(diào)用該函數(shù)并執(zhí)行我之后需要的操作的部分: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) => { }); });};這個(gè)問題就發(fā)生在 Promise.allSettled() 行。程序沒有等待 ship.layout.map() 生成的 promise,它會(huì)變成一個(gè)可迭代的數(shù)組,而是繼續(xù)執(zhí)行。我想這是因?yàn)?Promise.allSettled() 沒有等待 map() 生成數(shù)組才繼續(xù)前進(jìn),但一直無(wú)法解決問題,并且仍然懷疑這是解釋。誰(shuí)能告訴我我在這里做錯(cuò)了什么?如果我問的不清楚,請(qǐng)告訴我,我會(huì)盡力澄清。編輯:我懷疑它鏈接到 Promise.allSettled() 而不是等到 map() 填充數(shù)組以考慮數(shù)組內(nèi)的每個(gè)承諾都已解決,因?yàn)樗拈L(zhǎng)度在第 3 步似乎為 0,但我不確定。
JS - 在繼續(xù)下一部分之前未能正確解決一系列承諾
肥皂起泡泡
2022-12-29 16:18:30