使用mysql2 / promise库,我的一个对象部分包含以前SELECT语句中未解析的promise。
插入时,我收到错误的整数值错误消息,因为承诺尚未解决。什么是解决所包含的承诺的优雅方式?
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
});
答案 0 :(得分:2)
使用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;
});
});