用户定义函数终止时,Node.js回调函数

时间:2018-10-09 01:00:59

标签: node.js asynccallback

我有一个node.js应用程序,该应用程序包含一个计时器,该计时器调用由节点语言中的一堆函数组成的用户定义函数。调用脚本每10秒就有一个计时器调用函数mybuy(); mybuy()使用Binance api根据mySQL表(警报)中包含的触发价购买加密货币。我想在mybuy()运行后立即启动mysell()(未显示,但与myBuy()类似)。 如何使mysell()为mybuy()的回调函数?  这是调用脚本:

var fs = require('fs');
var sl = require('alberto/buy');
var loop = 0;

setImmediate(() => {
  // start the log
  fs.appendFile('./log.txt', "\n Loop-> " + loop + "\n", function (err) {
    if (err) { console.log(err); }
  })
  //execute the function  
  sl.mybuy(); // USD function; everything happens here.Can take long to finish
  var myInt = setInterval(function () {
    loop++;
    fs.appendFile('./log.txt', "Loop-> " + loop + "\n", function (err) {
      if (err) { console.log(err); }
    })
    //execute every 10 secs
    sl.mybuy();
    if (loop > 5) { clearInterval(myInt); } // max 6 loops for testing
  }, 10000);

});

此处的UDF ID

exports.mybuy = function () {
  var fs = require('fs');  // I keep a log.txt
  process.stdout.write("\u001b[2J\u001b[0;0H");// clear screen
  aww = (new Date()).toJSON().slice(0, 19).replace(/[-T]/, '-');
  aww = aww.replace(/T/, ' ');
  console.log(aww, '\n\n'); // practicing with dates
  var mysql = require('mysql');
  var con = mysql.createConnection({
    host: "www.photobangkok.com",
    user: "photoban_user",
    password: "xxxxxxxx",
    database: "photoban_datab"
  });
  // 'added' is for never processed entries in alarms table.It will change to BOUGHT or SOLD
  sql = "SELECT rec, id,coin,buy,amount_b,stat FROM alarms where stat='added' AND buy>0 order by coin";
  var cnt = 0; // not used, perhaps an idea to emit an event when cnt reaches the number of rows
  con.query(sql, function (err, result) {
    if (err) throw err;
    str = "";
    for (var index in result) {
      str = result[index].rec + "-" + result[index].id + "-" + result[index].coin + "-" + result[index].buy + "-" + result[index].amount_b + "-" + result[index].stat;
      // set up variables 
      coin = result[index].coin;
      buy = result[index].buy;
      rec = result[index].rec;
      id = result[index].id;
      amount = result[index].amount_b;
      console.log('\x1b[36m%s\x1b[0m', str); // set color green. Display str
      checkprice(coin, buy, rec, id, amount); //check Binance today price for the coin.The function will execute sometimes 
    }  // end of loop

    console.log('\x1b[36m%s\x1b[0m', str); // set color green. Display str
  });

  //check single coin price using binance api 
  function checkprice(coin, buy, rec, id, amount) {
    const binance = require('node-binance-api')().options({
      APIKEY: '<key>',
      APISECRET: '<secret>',
      useServerTime: true,
      test: true //sandbox does not work
    });
    binance.prices(coin, (error, ticker) => {
      act = "Nothing"; // default value
      pricenow = ticker[coin];  // note ticker[coin]
      if (pricenow < buy) {
        show(id, rec, coin, buy, amount, pricenow);// Display sometimes then call book()
      } else { console.log(coin, pricenow, buy, act, '\n'); }
    });

  }

  function show(id, rec, coin, buy, amount, pricenow) {
    delta = buy - pricenow; // posted trigger - today price
    delta = delta.toFixed(8);
    console.log('\x1b[31m%s\x1b[0m', coin, buy, amount, id, rec, ">BUY", delta); //display entries from alarms higher that today price
    book(id, rec, coin, buy, amount, pricenow);
  }
  // dummy function to be replaced with a buy api order
  function book(id, rec, coin, buy, amount, pricenow) {
    const binance = require('node-binance-api')().options({
      APIKEY: '<key>',
      APISECRET: '<secret>',
      useServerTime: true,
      test: true //sandbox 
    });
    console.log("Order:buy what??", coin, "amount:", amount, '\n');
    /* binance.prices(coin, (error, ticker) => {
    console.log("booking",coin, ticker[coin]);
    update(id,rec);
    }); */
    update(id, rec, amount); // update mySql table. Slow but sure
  }

  function update(id, rec, amount) {
    var sql = "UPDATE alarms SET stat = 'BOUGHT' ,today = 
    CONVERT_TZ(now(), '+00:00', '+7:00') WHERE id = "+id+" AND rec = "+rec;
    con.query(sql, function (err, result) {
      if (err) throw err;
      console.log(result.affectedRows + " record updated");
      // keep a log.tx
      fs.appendFile('./log.txt', aww + " bought " + id + "-" + rec + "-" + amount + "\n",
        function (err) {
          if (err) { console.log(err); }
        })
    });
  }
  // I could check if all rows are done and raise an event? (how to do it)
} // end 

1 个答案:

答案 0 :(得分:0)

要将mySell用作myBuy的回调方法,请使用以下结构调用myBuy方法。

myBuy(() => {
    // operation of mySell method
});

您的myBuy方法应该在执行自己的操作后返回回调。

exports.myBuy = function(cb) {
    // operation of myBuy method
    return cb; // return to the mySell method
}