слишком много return Promise javascript

169
12 февраля 2019, 03:30
 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')
            }
             })
          })
})
      }

Как правильно? и чтоб не было нагромождений

Answer 1

Вообще промисы сделали для того, чтобы избежать 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

Answer 2

Можно переписать с использованием 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; 
  } 
 
}

READ ALSO
Как написать кастомный цикл

Как написать кастомный цикл

Как все знают, существуют циклы while, do while и for в JavaScriptСделать кастомные циклы можно с помощью других циклов

164
Применение скобочной нотации в JavaScript

Применение скобочной нотации в JavaScript

Пожалуйста, объясните простыми словами, что дает скобочная нотация в JavaScript? Почему иногда это лучше, чем прямое присваивание свойству объекта?

160
Передача props между компонентами в React

Передача props между компонентами в React

У меня есть несколько компонентов по сути никак не связанных между собой, первый это ShoppingCards

170