function send_cash_toClient_QIWI(){
this.phone = this.tradeoffer.phone_number;
this.amount = this.tradeoffer.amount;
let msgProccess = (msg.send + this.phone + ' Количество: ' + this.amount + ' руб.');
return this.message(msgProccess).then((text) => {
return qiwi.send(One, this.amount, this.phone).then((status) => {
if(status){
console.log(this.id + ': ' + 'qiwi money was send');
this.payed = true;
this.save({'pay': true});
return this.message(msg.success).then((status) => {
return client.markpaid(this.id).then((status)=>{
return ('Marked as Payed');
})
})
} else {
return ('error send cash');
}
})
})
}
каждая функция внутри функции send_cash_toClient содержит промис(return new Promise) и возвращает resolve, поэтому после каждой функции .then((status), и я вызываю эту функцию (send_cash_toClie....) через await/async вопрос не переборщил ли я с return , изначально я написал так
function send_cash_toClient_QIWI(){
this.phone = this.tradeoffer.phone_number;
this.amount = this.tradeoffer.amount;
let msgProccess = (msg.send + this.phone + ' Количество: ' + this.amount + ' руб.');
return new Promise((resolve, reject) => {
this.message(msgProccess).then((text) => {
qiwi.send(One, this.amount, this.phone).then((status) => {
if(status){
console.log(this.id + ': ' + 'qiwi money was send');
this.payed = true;
this.save({'pay': true});
this.message(msg.success).then((status) => {
client.markpaid(this.id).then((status)=>{
resolve('Marked as Payed')
})
})
} else {
resolve('error send cash')
}
})
})
})
}
Как правильно? и чтоб не было нагромождений
Вообще промисы сделали для того, чтобы избежать callback hell, поэтому стоит их в общую цепочку объединять:
function send_cash_toClient_QIWI() {
this.phone = this.tradeoffer.phone_number;
this.amount = this.tradeoffer.amount;
let msgProccess = (msg.send + this.phone + ' Количество: ' + this.amount + ' руб.');
return this.message(msgProccess)
.then(text => qiwi.send(One, this.amount, this.phone))
.then(status => {
if (status) {
console.log(this.id + ': ' + 'qiwi money was send');
this.payed = true;
this.save({ 'pay': true });
return this.message(msg.success)
.then((status) => client.markpaid(this.id))
.then((status) => ('Marked as Payed'))
} else {
return ('error send cash');
}
})
}
Возвращая в then промис, его результат попадает в следующий then в одной цепи, а не в глубь.
Ну и в стрелочных функциях return коротких блоков пишется намного чище – (a) => { return a; }
можно записать как a => a
Можно переписать с использованием await/async
, будет немного более читабельно.
async function send_cash_toClient_QIWI() {
this.phone = this.tradeoffer.phone_number;
this.amount = this.tradeoffer.amount;
let msgProccess = (msg.send + this.phone + ' Количество: ' + this.amount + ' руб.');
try {
const text = await this.message(msgProccess);
const status = await qiwi.send(One, this.amount, this.phone);
if (status) {
console.log(this.id + ': ' + 'qiwi money was send');
this.payed = true;
this.save({'pay': true });
const statusSuccess = await this.message(msg.success);
const markpaidResult = await client.markpaid(this.id);
return 'Marked as Payed';
} else {
return 'error send cash';
}
} catch (e) {
return e;
}
}
Кофе для программистов: как напиток влияет на продуктивность кодеров?
Рекламные вывески: как привлечь внимание и увеличить продажи
Стратегії та тренди в SMM - Технології, що формують майбутнє сьогодні
Выделенный сервер, что это, для чего нужен и какие характеристики важны?
Современные решения для бизнеса: как облачные и виртуальные технологии меняют рынок
Как все знают, существуют циклы while, do while и for в JavaScriptСделать кастомные циклы можно с помощью других циклов
Пожалуйста, объясните простыми словами, что дает скобочная нотация в JavaScript? Почему иногда это лучше, чем прямое присваивание свойству объекта?
У меня есть несколько компонентов по сути никак не связанных между собой, первый это ShoppingCards