[英]Resolving promise object before MySQL INSERT
使用 mysql2/promise 庫,我的一個對象部分包含來自先前 SELECT 語句的未解析承諾。
插入時,我收到不正確的整數值錯誤消息,因為承諾尚未解決。 解決包含的承諾的優雅方法是什么?
let insertObj = {
author: this.authorId // unresolved promise #1
recipient: this.recipientId // unresolved promise #2
// ... more promises here
message: this.messageBody
}
let conn = this.pool.getConnection();
return conn.then((conn) => {
const res = conn.query("INSERT INTO posts SET ?", [insertObj]);
conn.release();
return res
});
使用async/await
:
async function f() {
// Prefix all promises with await
let insertObj = {
author: await this.authorId,
recipient: await this.recipientId,
// ... more promises here
message: await this.messageBody
}
let conn = this.pool.getConnection();
return conn.then((conn) => {
const res = conn.query("INSERT INTO posts SET ?", [insertObj]);
conn.release();
return res;
});
}
沒有async/await
你可以這樣做:
let insertObj = {
author: this.authorId,
recipient: this.recipientId,
// ... more promises here
message: this.messageBody
};
// Replace promises by their promised values as soon as they resolve:
Object.entries(insertObj).forEach( ([key, value]) => {
if (typeof Object(value).then === 'function') // it is a "thenable"
value.then ( response => insertObj[key] = response );
});
// Wait for all of them to resolve
Promise.all(Object.values(insertObj)).then( _ => {
let conn = this.pool.getConnection();
return conn.then((conn) => {
const res = conn.query("INSERT INTO posts SET ?", [insertObj]);
conn.release();
return res;
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.