0

I am currently developing a bot using wit.ai. I am quite new to node.js. Basically, I am following the guide provided by node-wit lib. I construct my wit object by:

const wit = new Wit({
  accessToken: WIT_TOKEN,
  actions,
  logger: new log.Logger(log.INFO)
});

In my actions, I have something like:

const actions = {
  send({sessionId}, {text}) {
     //my sending action goes here.
  },
  firstaction({context, entities,sessionId}) {
    var data = async_function();
    context.receiver = data;
    return context;
 }
}

The issue is that whatever comes after async_function will be executed first. I tried to let async_function return a promise. However, this wouldn't work since whatever comes after my first action in node-wit library will be executed first without waiting for the context to return. I don't want to modify the node-wit library.

Any idea that would solve my issue is appreciated!

Alex P.
  • 30,437
  • 17
  • 118
  • 169
Wei
  • 305
  • 5
  • 18

1 Answers1

2

you can use async library for asynchronous call

https://caolan.github.io/async/docs.html

const async = require('async')

const actions = {
  send({sessionId}, {text}) {
    //my sending action goes here.
  },
firstaction({context, entities,sessionId}) {
   async.waterfall([function(callback) {
    var d = async_function();
    // if err pass it to callback first parameter
    // return callback(err)
    callback(null,d);
 }], function(err, result) {
      if(err) {
         return err;
       }
      var data = result;
      context.receiver = data;
      return context;
   })
  }
}
parwatcodes
  • 6,669
  • 5
  • 27
  • 39
  • Thanks for your reference! I am just wondering if the function calling my firstaction is going to wait for the waterfall to finish? – Wei Jan 11 '17 at 18:16
  • I am quite not sure about how your code is running, `firstaction()` is a function call and you are returning context? could you please post `firstaction()` function definition, and `async_function()` definition too. – parwatcodes Jan 12 '17 at 04:07
  • Yes, the firstaction() is a function call that is returning context. Anyway, I solved it by using your way. It requires a bit restructure of my code tho. Thank you so much!. – Wei Jan 13 '17 at 01:20
  • That's Great Bro! #happyCoding – parwatcodes Jan 13 '17 at 04:59