簡體   English   中英

如何使用從exports.default 函數傳遞過來的變量

[英]How to use variable that is passed from exports.default function

我想找到訪問在另一個模塊的其他函數中用作參數的函數變量的最佳方法。 parsefile.js是一個 Node.js 腳本,導出為包模塊和兩個函數。 getfirstgetsecond需要訪問從 index.js 傳遞的變量,如'a', 'b' from parsefile('a', 'b', 'c') 除了使用global ,我們還有其他方法嗎?

// index.js from some application
const parsefile = require('./parsefile')
parsefile('a', 'b', 'c')


//parsefile.js exports about package module
function getfirst() {
  if (global.f && global.s) {
    return `i have totally 2 arguments: ${global.f}///${global.s}`
  }
  return `first arguments is ${global.f}`
}

function getsecond() {
  return `second arguments is ${global.s}`
}

module.exports = (...args) => {
  global.f = args[0];
  global.s = args[1];
  Promise.all([getfirst(), getsecond()]).then(([first, second]) => {
    console.log(`return from getfirst: ${first}`);
    console.log(`return from getsecond: ${second}`);
  });
}

不,不要使用全局變量! 只需將您的parsefile函數通過參數獲取的參數傳遞給您正在調用的函數:

function getfirst(f, s) {
  if (f && s) {
    return `i have totally 2 arguments: ${f}///${s}`;
  }
  return `first arguments is ${global.f}`;
}

function getsecond(s) {
  return `second arguments is ${s}`
}

module.exports = (f, s) => {
  Promise.all([
    getfirst(f, s),
    getsecond(s)
  ]).then(([first, second]) => {
    console.log(`return from getfirst: ${first}`);
    console.log(`return from getsecond: ${second}`);
  });
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM