从Express和Node的同步功能中调用异步(Promise)功能

时间:2018-10-28 14:59:42

标签: javascript express asynchronous promise async-await

从基本的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模块内部的调用之前。 getData给出undefined。似乎获得结果的唯一方法是在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(...)中实现相同的结果而无需实现async / await 功能?

非常感谢您的任何建议。

2 个答案:

答案 0 :(得分:1)

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

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,您的函数将不再同步抛出或错误。

答案 1 :(得分:-1)

任何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', async (req, res) => { const lang = req.params.lang; const results = await getData( lang ); res.json(results); }); 函数将始终返回Promise。 express支持返回承诺的路由处理程序。您可以使用以下代码:

{{1}}