【问题标题】:How to use callback in .then() function in Nodejs?如何在 Nodejs 的 .then() 函数中使用回调?
【发布时间】:2020-07-31 03:49:32
【问题描述】:

我有 nodejs 模块来使用 mongodb 驱动程序从 mongodb 数据库中获取数据。回调被传递给给定的函数,该函数返回一个承诺,但不是在 .then() 函数中返回结果,而是将值传递给回调函数。我如何从其他模块或函数调用此函数,因为它没有在 .then() 中返回它?我试图控制 .then() 的结果,但它显示未定义。

const MongoClient = require('mongodb').MongoClient;
const Db = require('../model/db');

Db.findUser = (details, callback) => {
    return dbconnection().then(db => {
        if (db) {
          return db.collection('users').findOne({
            email: details.email,
            pass: details.password
          }).then(data => {
            if (data) {
              console.log('Found one');
              callback(true);
            } else {
              let err = new Error();
              callback(err);
            }
          })
        }

我使用以下函数来调用承诺。我对 Promise 不熟悉。

var getUser = function(callback) {
  db.findUser().then(result => {
    console.log(result) // undefined
  })
}

【问题讨论】:

    标签: javascript node.js mongodb promise callback


    【解决方案1】:

    您可以使用async/await 轻松完成此操作。像这样的:

    Db.findUser = async (details, callback) => {
      const db = await dbconnection();
      const data = await db.collection('users').findOne({
        email: details.email,
        pass: details.password
      });
    
      if (data) {
        console.log('Found one');
        callback(true);
      } else {
        let err = new Error();
        callback(err);
      }
    
      return data;
    }
    

    然后像这样消费它:

    const getUser = async (details, callback) => {
      const data = await Db.findUser();
    
      // do whatever you need with data  
    
      return data;  
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-07
      • 2019-09-10
      • 1970-01-01
      • 2019-10-17
      相关资源
      最近更新 更多