const Controller = function(){
var busy = false;
return {
ready: () => busy === false,
do: (data) => new Promise((resolve,reject) => {
if (busy)
reject("I`m busy dude!")
busy = true;
// +100500 code rows
setTimeout(() => {
busy = false;
resolve("wow, its working fine!");
}, 1000);
})
}
}
let ctrl = new Controller();
ctrl.do("something")
.then(result => console.log("Job's done: " + result))
ctrl.do("fault")
.catch(err => console.log(`Houston, we have a problem: ${err}`));
setTimeout(() => ctrl.do("something again").then(result => console.log("It works again: " + result)), 1100)
function ConvertMainFunc(folder_path) {
try{
console.log("f-path in func:"+folderpath.value);
let txtlisttosend;
if(fs.existsSync(path2)){
getdirectories(folder_path.value, function(err, content){return content});
// return куда?
console.log(content);
// где определена переменная content?
function getdirectories(path, callback) {
fs.readdir(path, function (err, content) {
if (err) return callback(err)
console.log(content);
callback(null, content)
})
}
const company_data = () => new Promise((resolve,reject) => {
pool.query(`select * from the_company where creator_id = ?`, {creator_id}, (error,results,fields) => {
const id = results.map(r => r.id)
const name = results.map(r => r.name) //Ответ - { id: '41' } - id
console.log(`${id} - id`)
resolve(id)
})
})
reconnectTries: 2, // попытки реконнекта
reconnectInterval: 1000, //каждую секунду
connectTimeoutMS: 2000, // после 2 секунд ожидания соединения пытаться снова или сбрасывать
db.on('reconnected', function(){ console.log('reconnected successfully'});
db.on('reconnectFailed', function (error){
//Что делать если все попытки реконнекта провалились
});
var a = [123, 125, 555];
delete a[1];
console.log(a);
//[123, null, 555]
a.splice(1,1); // первое число это индекс, второе - количество удаляемых. Функция вернёт удаленные элементы, поэтому просто её вызываем
console.log(a);
// [123, 555]
a = a.filter( (index, value) => index != 1 );
console.log(a);
// [123, 555]
var _MR=0;
bot.addScene('sample',
({ reply, scene: { next } }) => {
next()
reply('Введите MR(целое число)');
},
({ reply, body, scene: { next } }) => {
_MR=parseInt(body);
next()
reply('Введите TR(целое число)')
},
({ reply, body, scene: { leave } }) => {
leave()
let kmr = _MR / parseInt(body)
reply(`KMR = ${kmr}`)
}
);
bot.command('Рассчитать коэффициент маржинального дохода', ({ scene: { join } }) => join("sample") );
var Offer = function(_chats, _task){
this.sendedTo = [];
this.user = '';
this.task = _task;
this.tMsg = `Заказ #${_task.id}\n${_task.info}\nСтоимость: ${_task.cost}`;
for (chat of _chats){
bot.sendMessage({
chat_id: chat,
text: this.tMsg,
reply_markup: {
text: 'беру',
callback_data: _task.id
}
}).then((result)=>this.sendedTo.push({id: result.chat, msg: result.message_id}));
}
}
bot.addUpdateListener((upd)=>{
function offerComplete(chat, msg){
bot.editMessageText({
chat_id: chat.id,
message_id: chat.msg,
text: msg,
reply_markup: null
});
}
if ('callback_data_id' in upd){
if (let offer = offers.find(i=>i.task.id === upd.data)){
if (offer.user === '' || upd.time < offer.time){
offer.user = upd.from.id;
offer.time = upd.time;
db.updateOfferInfo({telegramUserId: upd.from.id});
let msg = `\nЗаказ принял: @${upd.from.username}`;
if (/Заказ принял/i.test(offer.tMsg)) offer.tMsg=offer.tMsg.replace(/Заказ принял:\s@.*/i, msg);
else offer.tMsg += msg;
for (chat of offer.sendedTo){
offerComplete(chat, offer.tMsg);
}
}
else {
let chat = offer.sendedTo.find(i=>i.id === upd.chat);
offerComplete(chat, offer.tMsg);
}
}
}
});
var offers = [];
offers.push(new Offer([
...chats_id
],{
info: "Some offer for sales",
cost: 1000,
id: id_from_db
}));
expressServer.post('/', function (req, res) {
fs.readFile(req.files.inputFieldName.path, function (err, data) {
// inputFieldName - имя input в форме
var newPath = __dirname + "/uploads/uploadedFileName";
fs.writeFile(newPath, data, function (err) {
res.redirect("back");
});
});
});
console.log(`<Buffer ${(137).toString(16)} ${(80).toString(16)} ${(78).toString(16)}`)
let buffer = new Buffer.from("example");
console.log(buffer);
// <Buffer 65 78 61 6d 70 6c 65>
let json = buffer.toJSON();
console.log(json);
// {type: "Buffer", data: [ 101, 120, 97, 109, 112, 108, 101 ] }
let example = new Buffer.from(json);
console.log(example);
// <Buffer 65 78 61 6d 70 6c 65>
function printBuffer(buffer){
console.log(buffer);
}
printBuffer(example);
//<Buffer 65 78 61 6d 70 6c 65>