首页 > 解决方案 > 使用 Express 和 Node 从同步函数中调用异步(Promise)函数

问题描述

从基本的 express index.js 文件中,有没有办法从同步函数调用(这里的getData)中调用异步函数?

const express = require('express');
const bodyParser = require('body-parser');

// function which calls a Promise
const getData = require('./getAsyncData.js');

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/authors/:lang', (req, res) => { 

  const lang = req.params.lang; 
  const getResults = getData( lang );
  res.json(getResults);

});

这就是 getAsyncData 模块的样子:

// getAsyncData.js

const getAsyncData = async function () {

  try {

    // Questionable method of recovering the lang parameter here.
    const lang = (arguments.length) ? arguments[0].toUpperCase() : null;

    // Connect to the database
    const connection = await db.connect(true);

    // Get the data
    const {authors, books} = await connection.load();

    // Join results and filter it
    const filtered_results = GetAuhtorsBooks(authors, books, lang);

    // Send it back 
    return filtered_results;

  } catch(e) {

    return null;

  }

};

module.exports = getAsyncData;

但是在index.js调用中getData不可避免地发生在getAsyncData模块内部的调用之前。getDataundefined. 似乎获得结果的唯一方法是在index.js

app.get('/authors/:lang', async (req, res, next) => {

  try {
    const lang = req.params.lang;
    const testResult = await runTests(lang);
    res.json(testResult);

  } catch (e) {

    //this will eventually be handled by the error handling middleware
    next(e) 

  }

});

有没有 在 app.get(...) 中实现异步/等待功能的情况下获得相同结果的方法?

非常感谢您的任何建议。

标签: javascriptexpressasynchronouspromiseasync-await

解决方案


您可以使用较低级别的 API.then()

app.get('/authors/:lang', (req, res, next) => { 

  const lang = req.params.lang; 
  getData( lang )
    .then(getResults => res.json(getResults));
    .catch(next);

});

但在这一点上,你最好使用async,尤其是当你的代码达到一个点,即只获取一个数据点并返回它是不够的,你需要做更多的事情。

您仍然需要手动调用,next()或者res.error(...)无论如何,一旦涉及 Promise,您的函数将不再同步抛出或错误。


推荐阅读