我正在學習 Javascript,并且我上了一個關于 Promises 的部分。所以決定嘗試將我早期的一些專案轉換為使用 Promises。但我無法理解它。我閱讀了很多指南并瀏覽了該站點,但我仍然無法理解為什么這不起作用。
這是我正在使用的函式,試圖執行一個回傳承諾的資料庫呼叫,然后可以記錄或其他任何內容。
const getID = function (product) {
let query = `select typeID from invTypes where UPPER(typeName) =UPPER('${product}')`;
return new Promise((resolve, reject) => {
resolve(
DB.get(query, function (err, result) {
if (err) {
Bot.say(`Error looking up ${product}`);
} else {
console.log(result.typeID); //587
return result.typeID;
}
})
);
});
};
getID(product).then((data) => console.log(data)); //Database {}
控制臺輸出
Database {}
587
所以 .then(data => console.log(data)) //Database {} 在 promise 回傳之前仍在發生,
正如您所看到的,函式內部的其他日志實際上是在它之后記錄的。
有人可以幫我解決這個問題嗎?我已經在這個功能上作業了好幾個小時了,哈哈。我想我有某種根本性的誤解,我沒有從我的訓練營視頻或任何我閱讀的內容中發現。
uj5u.com熱心網友回復:
在 Promise 代碼中,您使用resolve()異步函式的回呼函式來回傳值。
const getID = function(product) {
let query = `select typeID from invTypes where UPPER(typeName) =UPPER('${product}')`;
return new Promise((resolve, reject) => {
DB.get(query, function(err, result) {
if (err) {
Bot.say(`Error looking up ${product}`);
reject(`Error looking up ${product}`);
} else {
console.log(result.typeID); //587
resolve(result.typeID);
}
})
});
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/421806.html
標籤:
上一篇:javascript/typescript-通過eslint規則強制將物件作為函式引數傳遞
下一篇:如何為我的網頁制作一個贊按鈕?
