0

Here is the test for the function I am trying to write.

 var chai = require('chai');
 var doLater = require('../05-callback');
 var expect = chai.expect;

describe('05-callback', function () {
 it('Can get secret number', function (done) {
  doLater(function (secret) {
   expect(secret).to.equal(1337);
   done();
  });
 });
});

I have written code that log's a message to the console asynchronously however, this code does not return the 1337 value asynchronously.

function doLater(secret) {
 var code = 1337;
 (function setImmediate(code) {
  console.log("I will be executed immediately");
  return code;
 })(code);
 setTimeout(function secret(code) {
  console.log("I will be executed in 2 seconds.");
  return code;
 }, 2000);
}

Please let me know if this post is not clear and I will edit it. Forgive me if this post is redundant, the simular post's I found were to advanced for me. Thank you for your help!

Paul VanDyke
  • 31
  • 1
  • 1
  • 6

1 Answers1

2

In order to do what you want to do, you need to use a callback. Example:

function doLater(callback) {
  setTimeout(function(){
    //after 2 seconds call the callback
    return callback(1337);
  }, 2000)
}

//pass as param a function that will be called
doLater(function(result) {
  console.log(result) //1337
})
yBrodsky
  • 4,981
  • 3
  • 20
  • 31