简体   繁体   English

Promise链怎么写?

[英]How to write Promise chain?

When I'm trying to make some database searching,I'd found two kind of codes to do this.But I don't know which is prefer and why..当我尝试进行一些数据库搜索时,我找到了两种代码来执行此操作。但我不知道哪种更喜欢以及为什么..

// a.js
export default oracledb.createPool(configuration)

the first way(it seems work well,but not meet the promise specifications):第一种方式(看起来效果不错,但不符合承诺规范):

// b.js
import main from a.js;
main.then((pool)=>{
    pool.getConnection().then((connection)=>{
        connection.execute(sql).then((result)=>{
           console.log(result);
           connection.close();
        }).catch(err=>{
           if(connection){connection.close()}
        })
    });
})

here is the second way:这是第二种方式:

let connection;
main.then((pool)=>{
    return pool.getConnection()
}).then((connection)=>{
   return connection.execute(sql)
}).then((result)=>{
   console.log(result);
   connection.close();
}).catch(err=>{
   if (connection){connection.close()}
});

This problem may not just about database operation, but the right way to organize promise chain.Can anyone please help me?这个问题可能不仅仅是数据库操作,而是promise链的正确组织方式。谁能帮帮我?

Use This Documentation https://oracle.github.io/node-oracledb/doc/api.html使用本文档https://oracle.github.io/node-oracledb/doc/api.html

const mypw = ...  // set mypw to the hr schema password

async function run() {

  let connection;

  try {
    connection = await oracledb.getConnection(  {
      user          : "hr",
      password      : mypw,
      connectString : "localhost/XEPDB1"
    });

    const result = await connection.execute(
      `SELECT manager_id, department_id, department_name
       FROM departments
       WHERE manager_id = :id`,
      [103],  // bind value for :id
    );
    console.log(result.rows);

  } catch (err) {
    console.error(err);
  } finally {
    if (connection) {
      try {
        await connection.close();
      } catch (err) {
        console.error(err);
      }
    }
  }
}

run();

One of main ideas to use promises is to avoid callback hell, but the first code you wrote also may become a cascade hell.使用 Promise 的主要思想之一是避免回调地狱,但您编写的第一个代码也可能成为级联地狱。 Second structure is better, and easier to read & debug:第二种结构更好,更易于阅读和调试:

let connection

main
.then(pool => pool.getConnection())
.then(connection => connection.execute(sql))
.then(result => {
   console.log(result)
   connection.close()
})
.catch(err => {
   if (connection) connection.close()
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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