Best way to return an exported module

时间:2019-01-07 13:03:55

标签: javascript node.js

On my learning journey, I have started to look at modules for javaScript/Node. What is confusing me is how to return information from a module when the time to complete the functions within a module is unknown.

This returns as expected:

controller.js

const myModule = require('./myModule');
var myWord = myModule.myExp();
console.log(myWord); //returns "Hello World"

myModule.js

module.exports = {
    myExp: function(){
        return mytimeOut();
    }
}

function mytimeOut(){
 var myWord = "Hello World";
 return myWord;
}

What I cannot seem to grasp, is the best way to return myModule when there is an indefinite time to bring back the required result.

How do I get the controller to show "Hello World" and not "Undefined" in the example below. I have read about callbacks, promises, async/await - but without any over-complications, I cannot seem to find a simple solution for this.

controller.js

const myModule = require('./myModule');
var myWord = myModule.myExp();
console.log(myWord); //returns undefined

myModule.js

module.exports = {
    myExp: function(){
        return mytimeOut();
    }
}

function mytimeOut(){
    setTimeout(() => {
        myWord = "Hello World";
        return myWord;

    }, 5000);
}

4 个答案:

答案 0 :(得分:1)

这是使用async / await的工作副本

from __future__ import print_function
import random
import sys

minimum, maximum = 1,69

def playPowerBall():
  instruction = "Please pick your {} number, between 1 and 69:"
  tickets = []
  for s in ('1st', '2nd', '3rd', '4th', '5th', '6th'):
    ticket = int(input(instruction.format(s)))
    tickets.append(ticket)

  if any(ticket < minimum or ticket > maximum for ticket in tickets):
    print('One or more of the inputted numbers is not between 1-69. Please restart the function and try again.')
    sys.exit()

  winners = []

  for s in ('1st', '2nd', '3rd', '4th', '5th', '6th'):
    winner = random.sample(range(0,69), 6)
    winners.append(winner)

  matches(tickets, winners)

def matches(tickets, winners):
  score = 0

  for number in tickets:
    if number in winners:
      score += 1
    else:
      score += 0

  if 3 <= score:
    print('You picked at least three winning numbers, please claim your cash prize.')
  else:
    print('You do not have a winning combination. Would you like to play Powerball again? (Y/N)')
    response = str(input('Y/N:'))

    if response == 'Y':
      playPowerBall()
    else:
      sys.exit()

playPowerBall()
const exports = {
  myExp: function() {
    return mytimeOut();
  }
}

function mytimeOut() {
  return new Promise((resolve) => {
    setTimeout(() => {
      const myWord = "Hello World";
      resolve(myWord);
    }, 5000);
  });
}

(async () => {
  const output = await exports.myExp();
  document.getElementById('output').textContent = output;
})();

答案 1 :(得分:1)

You can achieve that using async/await.

File: myModule.js

function myTimeout() {
  // Create a promise
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("Hello World"); // resove the promise after those 5 seconds
    }, 5000);
  })
}

module.exports = {
  myExp: function() {
    return myTimeout();
  }
};

File: controller.js

const myModule = require('./myModule');

async function findMyWord() {
  const myWord = await myModule.myExp();
  console.log('My word is:', myWord);
}

findMyWord();

I wrapped everything in an async function because otherwise you will receive the Syntax Error: await is only valid in async error.

答案 2 :(得分:0)

Using async/await:

  // myModule.js

  function mytimeOut() { 
    return new Promise(resolve => 
      setTimeout(() => resolve('Hello World'), 5000)
    )
  }

  // controller.js

  async function init() {
    var myWord = await myModule.myExp()
    console.log(myWord)
  }
  init()

答案 3 :(得分:0)

您需要使用Promise,因为setTimeout不会返回可以等待的承诺。

文件: myModule.js

'use strict';

module.exports = {
  myExp: function() {
    return mytimeout();
  }
};

function mytimeout() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Hello World');
    }, 1000);
  }); 
}

文件: controller.js( .then()

'use strict';

const myModule = require('./myModule.js');
myModule.myExp().then(console.log);