我有一个简单的 node 模块,它连接到数据库,并具有多个接收数据的功能,例如:


dbConnection.js:

import mysql from 'mysql';

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'user',
  password: 'password',
  database: 'db'
});

export default {
  getUsers(callback) {
    connection.connect(() => {
      connection.query('SELECT * FROM Users', (err, result) => {
        if (!err){
          callback(result);
        }
      });
    });
  }
};

该模块将以这种方式从另一个 node 模块调用:


app.js:

import dbCon from './dbConnection.js';

dbCon.getUsers(console.log);

我希望使用promise 而不是回调来返回数据.

推荐答案

Using the Promise class

我建议看一看MDN's Promise docs,它为使用promise 提供了一个很好的起点.或者,我相信网上有很多教程.:)

Note:款现代浏览器已经支持ECMAScript 6promise 规范(参见上面链接的MDN文档),我假设您希望使用本机实现,而不使用第三方库.

作为一个实际的例子...

基本原理如下:

  1. 您的API被调用
  2. 创建一个新的Promise对象,该对象将单个函数作为构造函数参数
  3. 您提供的函数由底层实现调用,该函数有两个函数——resolvereject
  4. 一旦你完成了你的逻辑,你可以调用其中一个来完成promise ,或者用一个错误来拒绝它

这看起来可能很多,所以这里是一个实际的例子.

exports.getUsers = function getUsers () {
  // Return the Promise right away, unless you really need to
  // do something before you create a new Promise, but usually
  // this can go into the function below
  return new Promise((resolve, reject) => {
    // reject and resolve are functions provided by the Promise
    // implementation. Call only one of them.

    // Do your logic here - you can do WTF you want.:)
    connection.query('SELECT * FROM Users', (err, result) => {
      // PS. Fail fast! Handle errors first, then move to the
      // important stuff (that's a good practice at least)
      if (err) {
        // Reject the Promise with an error
        return reject(err)
      }

      // Resolve (or fulfill) the promise with data
      return resolve(result)
    })
  })
}

// Usage:
exports.getUsers()  // Returns a Promise!
  .then(users => {
    // Do stuff with users
  })
  .catch(err => {
    // handle errors
  })

使用异步/等待语言功能(Node.js>=7.6)

在 node 中.js 7.6,v8 JavaScript编译器升级为async/await support.现在可以将函数声明为async,这意味着它们会自动返回Promise,在异步函数完成执行时解析.在这个函数中,您可以使用await关键字等待另一个promise 得到解决.

下面是一个例子:

exports.getUsers = async function getUsers() {
  // We are in an async function - this will return Promise
  // no matter what.

  // We can interact with other functions which return a
  // Promise very easily:
  const result = await connection.query('select * from users')

  // Interacting with callback-based APIs is a bit more
  // complicated but still very easy:
  const result2 = await new Promise((resolve, reject) => {
    connection.query('select * from users', (err, res) => {
      return void err ? reject(err) : resolve(res)
    })
  })
  // Returning a value will cause the promise to be resolved
  // with that value
  return result
}

Node.js相关问答推荐

即使DDB键不存在, node Lambda也不会失败,并返回NULL作为结果

如果我加入另一个公会且我的​​机器人已在其中,欢迎消息发送错误

如何修复node.js中的错误代码无法加载资源:服务器响应状态为403(禁止)

如何使用Stripe测试失败的收费?

在mongoose虚拟属性中处理异步操作

Gulp 能否向 Docker 发出增量构建的第一次迭代完成的信号?

ResponseError:键空间ks1不存在

如何从动态Typescript 文件加载模块

(Mongoose) 删除 TTL 字段失败

Nodejs mongoose 在一个查询中从多个集合中获取结果

使用 firebase 函数 api 运行套接字(相同的端口创建问题)

使 pm2 登录到控制台

Mongodb v4.0 Transaction, MongoError: Transaction numbers are allowed on a replica set member or mongos

分块 WebSocket 传输

添加git信息到create-react-app

从目录 node Js 中检索文件

如何从 Node.js 中的 URL 获取

nodeJS - 如何使用 express 创建和读取会话

Javascript在try块内设置const变量

Node.js 中的 Streams3 是什么,它与 Streams2 有何不同?