我有一個在 NodeJS 上運行的 javascript 應用程式。對于背景關系,我使用的是 express 框架,因為它是我們的后端。我有一段代碼,旨在從資料庫中獲取資料,對其進行過濾,然后將其發送回客戶端。相反,過濾發生在回應發送之后,這意味著客戶端得到了不正確的資料。代碼如下。
let resultArray = [];
const bulkSearchPromise = new Promise((resolve, reject) => {
for (let index = 0; index < input.length; index ) {
collectionPool.query('SELECT * FROM users WHERE ' type ' = $1', [input[index]], (err2, result2) => { // Make a query for each input user is trying to search for
if (err2) console.log("Error in bulk search: " err2);
else {
if (result2.rows.length > 0) { // If input user searched for was found
pool.query('UPDATE users SET usedsearches = usedsearches 1 WHERE id = $1', [result.rows[0].id]); // Increments used searches
// The code below will filter useless key value pairs. For example if username: null then there is not a reason to send it back to the client
let filteredArray = [];
for (let index = 0; index < result2.rows.length; index ) {
let array = Object.entries(result2.rows[index]);
let filtered = array.filter(([key, value]) => value != null);
let filteredObject = Object.fromEntries(filtered);
filteredArray.push(filteredObject);
resultArray.push(filteredObject);
}
console.log("a"); // This should run first.
}
}
});
}
resolve("ok");
})
bulkSearchPromise.then((value) => {
console.log("b"); // This should run second
return res.json({
status: 'success',
content: resultArray
}); // resultArray should be populated after the filtering above. Instead it is empty.
})
當端點被擊中時,輸出將始終為
username
b
a
我需要的是 for 回圈首先運行,然后在填充 resultArray 后,將其回傳給客戶端。
我嘗試將這段代碼包裝成一個承諾,但這也沒有幫助,因為在 for 回圈完成之前仍然呼叫了 'resolve("ok")'。
uj5u.com熱心網友回復:
你的承諾在collectionPool.query我們完成之前就解決了。
for 回圈僅在collectionPool.query完成后運行,但您正在解決它之前的承諾。請注意,它collectionPool.query是異步的,它的回呼只會在 web-api 完成時運行(如果這個概念很模糊,請查看http://latentflip.com/loupe)
選項1:
移動resolve()到collectionPool.query(其中console.log("a");)回呼并呼叫resolve(filteredObject)。另外你應該reject(err2)什么時候err2不為空(不僅僅是控制臺)
選項 2:
您可以使用Util.Promisify轉換collectionPool.query來承諾基本 API,這將為您節省手動轉換的麻煩
const util = require('util');
util.promisify(collectionPool.query)(QUERY)
.then(queryRes => {
/* logic to refine queryRes to object */
return filteredObject;
})
resultArray在這兩個選項中,您都可以從代碼中省略。如果您resolve(filteredObject)或您將能夠在下一個(中的值)訪問return filteredObject;此資料。then()thenbulkSearchPromise.then((value)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/530121.html
上一篇:在示例中使用`.then`與async/await功能差異
下一篇:如何在回圈中命令Ajax呼叫
