Node.js функция обратного вызова при завершении определенной пользователем функции - PullRequest
0 голосов
/ 09 октября 2018

У меня есть приложение node.js, состоящее из таймера, вызывающего пользовательскую функцию, составленную из набора функций на языке узлов.Вызывающий скрипт имеет функцию таймера вызова mybuy () каждые 10 секунд;mybuy () покупает криптовалюты с использованием API Binance в соответствии с ценами триггера, содержащимися в таблице MySQL (аварийные сигналы).Я хотел бы запустить mysell () (не показано, но похоже на myBuy ()) сразу после выполнения 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 здесь

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 голосов
/ 09 октября 2018

Чтобы сделать mySell методом обратного вызова myBuy, вызовите метод myBuy, используя следующую структуру.

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

И ваш метод myBuy должен вернуть обратный вызов после выполнения своей собственной операции.

exports.myBuy = function(cb) {
    // operation of myBuy method
    return cb; // return to the mySell method
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...