Reputation: 11
How can I send res.data.values to another module.js? And how can I get it in module.js? The code below is a piece of the code provided by the following link: https://developers.google.com/sheets/api/quickstart/nodejs
The res.data.values take some time to response, so I believe this is my main problem and I don't know how to handle this.
function listMajors(auth) {
const sheets = google.sheets({version: 'v4', auth});
sheets.spreadsheets.values.get({
spreadsheetId: '1XrmHL0D8HCulZYaB_ocrYlpnvqP9cO0BTJ14wHTGLis',
range: 'Ficha',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const rows = res.data.values;
if (rows.length) {
console.log(rows)
} else {
console.log('No data found.');
}
});
}
Upvotes: 1
Views: 251
Reputation: 8135
If I understand your problem correctly. You are looking for a solution for async data handling. There are many ques/answers you can find over the internet. But just to help fast, Please refer to the below answer.
//List.js
// Using callback
function listMajors(auth, cb) {
const sheets = google.sheets({ version: "v4", auth });
sheets.spreadsheets.values.get(
{
spreadsheetId: "1XrmHL0D8HCulZYaB_ocrYlpnvqP9cO0BTJ14wHTGLis",
range: "Ficha",
},
(err, res) => {
cb(err, res.data.values.length ? res.data.values : []);
}
);
}
exports.listMajors = listMajors;
// main.js
// in other module
const { listMajors } = require("./List");
listMajors("auth", (error, rows) => {
if (error) {
/// show error message
} else if (rows.length) {
// display rows
} else {
//display empty
}
});
Since Google sheets provide promisable method. You can simplify using async-await or promises. Below is an example using async-await
. You can simply use `promise-then
// Using async-await
//List.js
async function listMajors(auth) {
const sheets = google.sheets({ version: "v4", auth });
try {
const res = await sheets.spreadsheets.values.get({
spreadsheetId: "1XrmHL0D8HCulZYaB_ocrYlpnvqP9cO0BTJ14wHTGLis",
range: "Ficha",
});
return res.data.values.length ? res.data.values : [];
} catch (error) {
throw error;
}
}
exports.listMajors = listMajors;
// main.js
const { listMajors } = require("./List");
// in other module
async function main() {
try {
const rows = await listMajors("auth");
if (rows.length) {
// display rows
} else {
//display empty
}
} catch (error) {
/// show error message
}
}
main();
Upvotes: 1
Reputation: 109
The problem that you described can be solved with the pub-sub architecture:
There are many libraries that can achieve this, like Redis:
const express = require("express")
const redis = require("redis")
const subscriber = redis.createClient()
const app = express()
subscriber.on("message", (channel, message) => {
console.log("Received data :" + message)
})
app.get("/", (req, res) => {
res.send("subscriber two")
})
subscriber.subscribe("user-notify")
app.listen(3007, () => {
console.log("server is listening to port 3007")
})
Upvotes: 0