Может кто-нибудь объяснить, почему переменная api
недоступна в функции asyn c ниже? Я могу добраться до него, когда начинаю общаться с процессом рендеринга, но как только я вызываю функцию asyn c, она становится недоступной. Что я здесь не так делаю?
ОШИБКА:
ERR: err getting data async in main: ReferenceError: api is not defined
MAIN.ts
import { app, BrowserWindow, ipcMain } from "electron";
import * as path from "path";
import { CandleRes } from "./models";
let mainWindow: Electron.BrowserWindow;
let api: any;
async function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({
height: 600,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
nodeIntegration: true //https://stackoverflow.com/questions/44391448/electron-require-is-not-defined
},
width: 800
//backgroundColor: "#FFF"
});
// and load the index.html of the app.
mainWindow.loadFile(path.join(__dirname, "../index.html"));
// Open the DevTools.
//mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.on("closed", () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
//-----setup oanda data
await setupApi();
console.log("api setup complete: " + JSON.stringify(api) + "\n");
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
//const template=[{label:'test',submenu:[{label:'copy',accelerator:'Ctrl+C',role:'copy'}]}]
//Menu.buildFromTemplate(template);
app.on("ready", () => {
createWindow();
});
// Quit when all windows are closed.
app.on("window-all-closed", () => {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", async () => {
// On OS X it"s common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow();
}
});
// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
//async msg gets ref to window
ipcMain.on("start-comm", async (event, arg) => {
console.log("main got: " + arg);
//replies async with real data
if (api) {
console.log("MAIN API: " + JSON.stringify(api));
let candles = await getDataAsync();
event.reply("asynchronous-data", candles);
} else {
console.log("API NOT LOADED/ACCESSIBLE");
}
//if sync reply: event.returnValue = 'pong'
});
async function getDataAsync(): Promise<CandleRes> {
let candles: CandleRes = {} as CandleRes;
try {
candles = (
await api.getCandles("USD_CAD", {
granularity: "M5",
count: 1
})
).data;
} catch (e) {
console.log("ERR: err getting data async in main: " + e);
}
return candles;
}
async function setupApi() {
var key = ""; //https://www.oanda.com/demo-account/tpa/personal_token
var acctid = "";
const Oanda = require("oanda-node-api");
const config = {
env: "fxPractice",
auth: `Bearer ${key}`,
accountID: acctid,
dateFormat: "RFC3339"
};
api = Object.create(Oanda); //<<<ERR below fires here
api.init(config);
}
ВЫХОД
настройка API завершена: {ДЕЙСТВИТЕЛЬНЫЙ ОБЪЕКТ ЗДЕСЬ}
основной получил: готов к приему данных
ОСНОВНОЙ API: {ДЕЙСТВИТЕЛЬНЫЙ ОБЪЕКТ ЗДЕСЬ}
Я экспериментировал с изменением api
на this.api
но получил эту ошибку:
UnhandledPromiseRejectionWarning: TypeError: Невозможно установить свойство 'api' undefined в C: \ Users ... \ Electron-ts \ dist \ main. js : 168: 22 * 1025 *