本文介绍了如何获取Express Node路由以在渲染之前等待功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取一条路径,以等待另一个模块中的异步功能在渲染运行之前返回,但是无论我做什么, res.render 总是首先运行.这是我当前的代码,实际上只是冻结而从不加载:

I am trying to get a route to wait for an async function in another module to return before render runs, but no matter what I do, res.render always runs first.This is my current code, which actually just freezes and never loads:

router.get('/', function(req, res, next) {
  try {
    const cities = spreadsheet.getData()

  } catch(err) {
    console.log(err)
  }

  res.render('index', { cities: cities})
})

它正在等待的功能是这样的:

and the function it is waiting for is this:

exports.getData = function () {
  parsedData = [];
  accessSpreadsheet().then(function(data) {
    console.log(parsedData)
    return parsedData;
  });
};

const accessSpreadsheet = async() => {
  await doc.useServiceAccountAuth({
      client_email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
      private_key: process.env.GOOGLE_PRIVATE_KEY,
    });
  const loadedDoc =  await doc.loadInfo();
  sheet = await doc.sheetsByIndex[0];
  const cells = await sheet.loadCells(allCells[cellsIndex]);
  const data = await parseData();
  const moreCells = await checkNextCells()

  return;
}

首先运行渲染,然后在控制台中打印 parsedData .我还尝试使路由异步,并在回调中尝试了 res.render .有什么办法可以做到这一点?

The render runs first, and the parsedData prints in the console. I also tried making the route async, and I tried res.render inside a callback. Is there any way to make this work?

推荐答案

由于 accessSpreadSheet async 函数,因此您要么需要 await 或在getData函数中以及类似地在路由器中返回诺言(如Patrick Patricks在评论中所建议).

Since accessSpreadSheet is an async function, you either need to await or return the promise (as suggested by Patrick Roberts in the comment), in getData function, and similarly in the router.

使用异步等待,您可以按以下方式更新代码(未经测试)

Using async await you can update your code as below (not tested)

exports.getData = async function () {
  parsedData = [];
  parsedData = await accessSpreadSheet();
  return parsedData;
};

const accessSpreadsheet = async() => {
  await doc.useServiceAccountAuth({
      client_email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
      private_key: process.env.GOOGLE_PRIVATE_KEY,
    });
  const loadedDoc =  await doc.loadInfo();
  sheet = await doc.sheetsByIndex[0];
  const cells = await sheet.loadCells(allCells[cellsIndex]);
  const data = await parseData();
  const moreCells = await checkNextCells()

  return;
}

在路由器中

router.get('/', async function(req, res, next) {
  let cities;
  try {
    cities = await spreadsheet.getData()

  } catch(err) {
    console.log(err)
  }

  res.render('index', { cities: cities})
})

这篇关于如何获取Express Node路由以在渲染之前等待功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 13:38
查看更多