我的 MERN 后端有这个功能(M 不是用于 Mongo 而是 MySQL)应用程序。此函数异步获取数据库中的所有股票并将其作为回调返回。
getAllStocks: function(callback) {
var context = dbContext.create();
// First select the stock to get its price
context.query(`SELECT * from Stock`, function(err, result) {
if (err) throw err;
module.exports.stocks = callback(err, result);
});
return result;
}
我试图在这一行的一个变量中导出回调:
module.exports.stocks = callback(err, result);
并在我的 React App 中调用它
import { stocks } from '../../Backend/StockFunctions';
import mysql from 'mysql';
import './App.css';
import React, { Component } from 'react'
export default class App extends Component {
constructor() {
super();
this.state = {
stocks: []
}
}
async componentDidMount() {
console.log(stocks);
}
我已经尝试过这种方式,它会打印一个空数组。
我也尝试将功能更改为:
getAllStocks: function(callback) {
var context = dbContext.create();
// First select the stock to get its price
context.query(`SELECT * from Stock`, function(err, result) {
if (err) throw err;
callback(result);
// Make sure that the user has enough of the stock to sell it (amout <= total stock qty)
});
}
并这样称呼它:
async componentDidMount() {
getAllStocks(function(result) {
return result;
})
}
然后这是它返回的错误:
我应该怎么做?