繁体   English   中英

在 MySQL INSERT 之前解析 promise 对象

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM