קורס Node.JS שיעור האוביקט exports


זה נושא דיון מלווה לערך המקורי ב- https://www.tocode.co.il/bundles/nodejs/lessons/07-exports

נהנתי מאוד מהפרק הה , הדברים הובנו הרבה יותר!
פתאום הבנתי מה זה const app = express();

לייק 1

Hi Yinon!
It was interesting point about exports value calculated only once.
.Yet it was in sync manner.
And what if I want to perform async calculation only once and export it?
for multiple reuse?
I am trying, yet getting error
TypeError: require(…).then is not a function:

//============randomNumbersAsync.js
exports.numbers = async function randomNumbers() {
    const numbers = [];
    for (let i = 0; i < 3; i++) {
        let num = Math.floor(Math.random() * 100);
        numbers.push(num);
    }
    return numbers;
}();
//=================index.js

app.get('/', (req, res) => {
    require('./randomNumbersAsync').then( rnData => {
        res.send(`Hello / ${rnData.numbers.toString()}`)
    })
})

Hi,

This looks in the right direction however notice that randomNumbers is now a promise,
so the index.js code that uses it should be like:

const result = (await rnData.numbers()).toString();

Thank you!
That’s worked for me

//asynNum.js
async function asyncFunc()
{
    return 17;
}

module.exports.numPromise = asyncFunc();
//index.js
const {numPromise} = require("./asyncNum");
numPromise.then( num => {
    console.log("v1: ",num);
})

require("./asyncNum").numPromise.then( num => {
    console.log("v2: ",num);
})

היי
יש לי שאלה לא קשורה ספציפית לשיעור הזה, אבל הוא ממש הבהיר המון דברים!!
שמתי לב שבתקיית התרגילים, לכל תרגיל יש בפנים package ו - package-lock, האם אתה עושה npm init לכל תרגיל שאתה פותח?

הי,

אני כן אבל אפשר גם לשים את הקבצים האלה בתיקייה הראשית, כלומר בתיקיה שמכילה את כל התיקיות התרגילים ואז יהיה צריך npm init ו npm install רק פעם אחת