How to return within the "then" chain for Angular?

Viewed 31

Pseudocode

doStuff() {
  // A is an asynchronous call
  A
  .then(result_a => { // process result_a })
  .then(result_b => { // process result_b })
  .then(() => { // side_effects})
}

How to return result_b?


Background

I'm using TypeORM to save an order and order lines to a sqlite database for an angular+electron desktop application. I don't think this is specific to Angular. I'm not too familiar with using then other than chaining them in a very linear fashion.

Problem Statement

How do I return the purchase_order which is in the middle of the then chain? I'm looking for this or the purchase_order.id.

Stripped down version:

addOrder(header: PurchaseOrder, lines: PurchaseOrderLine[]) {
  const new_order = new PurchaseOrder();

  this.databaseService.connection
    .then(conn => conn.manager.save(new_order))
    .then(purchase_order => {
      let new_lines = lines.map(line => {
        const new_order_line = new PurchaseOrderLine();
        this.databaseService
          .connection
          .then(conn => conn.manager.save(new_order_line));
      })
    })
    .then(() => this.reflectChanges());
}

Fuller version:

addOrder(header: PurchaseOrder, lines: PurchaseOrderLine[]) {
  const new_order = new PurchaseOrder();

  // copy header details to new order
  new_order.purchase_order_date = (<any>header.purchase_order_date).format();
  new_order.total_value = header.total_value;
  if(header.delivery_required_by) {
    new_order.delivery_required_by = (<any>header.delivery_required_by).format();
  }
  new_order.notes = header.notes;
  new_order.supplier = _state.selectedSupplier;

  // use databaseService to save order and then save the order lines
  this.databaseService
    .connection
    .then(conn => conn.manager.save(new_order))
    .then(purchase_order => {
      let new_lines = lines.map(line => {
        const new_order_line = new PurchaseOrderLine();

        new_order_line.quantity = line.quantity
        new_order_line.code = line.code
        new_order_line.file_no = line.file_no
        new_order_line.description = line.description
        new_order_line.unit = line.unit
        new_order_line.rate = line.rate
        new_order_line.total = line.total
        new_order_line.note = line.note
        new_order_line.purchase_order = purchase_order

        this.databaseService
          .connection
          .then(conn => conn.manager.save(new_order_line));
      })
    })
    .then(() => this.reflectChanges());
}
0 Answers
Related