【问题标题】:How can i handle this promise correctly?我怎样才能正确处理这个承诺?
【发布时间】:2021-04-01 04:03:28
【问题描述】:

所以我使用 WooCommerce API 来带来我当前 wordpress 的产品。我使用 Nestjs 作为后端,使用 Postman 来发出请求。

这是我的控制器

@Controller('game')
export class GameController {
  constructor(private readonly gameService: GameService) {}

  @Get()
  findAll() {
    this.gameService.test().then((data) => {
      return data;
    });
  }
}

这是我的服务,我在其中连接到 WooCommerce API

import WooCommerce from '../config/woocomerce.config';

@Injectable()
export class GameService implements GameServiceInterface {
  async test() {
    try {
      const response = WooCommerce.get('products');
      response.then((data) => {
        console.log(data.data);
      });
    } catch (err) {
      return `Error! ${err}`;
    }
  }
}

问题是,当我在控制台记录承诺数据字段时,它工作正常!,这里是 输出

[
gm-commerce-backend |   {
gm-commerce-backend |     id: 10,
gm-commerce-backend |     name: 'Test product',
gm-commerce-backend |     slug: 'test-product',
gm-commerce-backend |     permalink: 'http://wordpress/product/test-product/',    
gm-commerce-backend |     date_created: '2020-12-21T14:27:07',
gm-commerce-backend |     date_modified: '2020-12-21T14:27:14',
gm-commerce-backend |     type: 'simple',
gm-commerce-backend |     status: 'publish',
gm-commerce-backend |     featured: false,
gm-commerce-backend |     catalog_visibility: 'visible',
gm-commerce-backend |     description: '<p>This is a test product for the WooCommerce API connection</p>\n',
gm-commerce-backend |     short_description: '',
gm-commerce-backend |     sku: '',
gm-commerce-backend |     price: '588',
gm-commerce-backend |     regular_price: '2002',
gm-commerce-backend |     sale_price: '588',
gm-commerce-backend |     date_on_sale_from: '',
gm-commerce-backend |     date_on_sale_to: '',
gm-commerce-backend |     price_html: '<del><span class="woocommerce-Price-amount 
amount"><bdi><span class="woocommerce-Price-currencySymbol">&#36;</span>2,002.00</bdi></span></del> <ins><span class="woocommerce-Price-amount amount"><bdi><span class="woocommerce-Price-currencySymbol">&#36;</span>588.00</bdi></span></ins>',    
gm-commerce-backend |     on_sale: true,
gm-commerce-backend |     purchasable: true,
gm-commerce-backend |     total_sales: 0,
gm-commerce-backend |     virtual: false,
gm-commerce-backend |     downloadable: false,
gm-commerce-backend |     downloads: [],
gm-commerce-backend |     download_limit: -1,
gm-commerce-backend |     download_expiry: -1,
gm-commerce-backend |     download_type: 'standard',
gm-commerce-backend |     external_url: '',
gm-commerce-backend |     button_text: '',
gm-commerce-backend |     tax_status: 'taxable',
gm-commerce-backend |     tax_class: '',
gm-commerce-backend |     manage_stock: false,
gm-commerce-backend |     stock_quantity: null,
gm-commerce-backend |     in_stock: true,
gm-commerce-backend |     backorders: 'no',
gm-commerce-backend |     backorders_allowed: false,
gm-commerce-backend |     backordered: false,
gm-commerce-backend |     sold_individually: false,
gm-commerce-backend |     weight: '',
gm-commerce-backend |     dimensions: { length: '', width: '', height: '' },      
gm-commerce-backend |     shipping_required: true,
gm-commerce-backend |     shipping_taxable: true,
gm-commerce-backend |     shipping_class: '',
gm-commerce-backend |     shipping_class_id: 0,
gm-commerce-backend |     reviews_allowed: true,
gm-commerce-backend |     average_rating: '0.00',
gm-commerce-backend |     rating_count: 0,
gm-commerce-backend |     related_ids: [],
gm-commerce-backend |     upsell_ids: [],
gm-commerce-backend |     cross_sell_ids: [],
gm-commerce-backend |     parent_id: 0,
gm-commerce-backend |     purchase_note: '',
gm-commerce-backend |     categories: [ [Object] ],
gm-commerce-backend |     tags: [],
gm-commerce-backend |     images: [ [Object] ],
gm-commerce-backend |     attributes: [],
gm-commerce-backend |     default_attributes: [],
gm-commerce-backend |     variations: [],
gm-commerce-backend |     grouped_products: [],
gm-commerce-backend |     menu_order: 0,
gm-commerce-backend |     _links: { self: [Array], collection: [Array] }
gm-commerce-backend |   }
gm-commerce-backend | ]

但是在 Postman 中什么都没有出现。我得到一个空白页。

这是邮递员输出

我期待什么?,我希望在我的控制台中显示相同的输出,但在邮递员中。

【问题讨论】:

  • 你可能想return Promise in findAll
  • 但是如果我在控制器中返回我的承诺,我将无法处理承诺
  • “处理”是什么意思?您仍然可以在其中有一个.then,无论您在其中返回什么,都将是解析后的数据。
  • 所以在我的服务中我会做一些像const response = WooCommerce.get('products'); return response;
  • 但是你不是在等待承诺。为了清楚起见,您知道您不能简单地从.then 中的findAll 中的return 的东西,并期望它是调用findAll 的返回值? findAll 需要返回一个 Promise,否则你怎么能等待它解决呢?在您的服务中,您已经在使用response.then 进行操作。只是你没有findAll返回这个Promise...

标签: javascript node.js promise backend nestjs


【解决方案1】:

你应该添加async,然后在Controller中返回你的gamsService承诺结果。

@Controller('game')
export class GameController {
  constructor(private readonly gameService: GameService) {}

  @Get()
  async findAll() {
    // you also could not add await, nestjs will help you to get the promise value.
    // it'll work with or without adding await.
    return await this.gameService.test()
  }
}

你还需要在Service中返回promise。

import WooCommerce from '../config/woocomerce.config';

@Injectable()
export class GameService implements GameServiceInterface {
  async test() {
    try {
      // return all fields
      return WooCommerce.get('products');
      
      // return only header field
      const config = await WooCommerce.get('products')
      return {
          header: config.header
      }
    } catch (err) {
      return `Error! ${err}`;
    }
  }
}

注意:你可以看到nestjs - Asynchronicity

【讨论】:

  • 这行得通,我已经读过嵌套解决了 Promise,但是如果我想访问我的数据的特定字段,我不想要所有的 .then 数据,我想要,让我们作为一个例子:data.header
  • 谢谢!!它现在完美无缺。因此,为了清楚起见并出于学习目的,在我的控制器中,我应该始终返回一个承诺,对吗?
  • 当你在函数前面添加异步时,无论你返回什么都是承诺值。
猜你喜欢
  • 2016-08-28
  • 1970-01-01
  • 2021-06-07
  • 2016-06-15
  • 2021-09-24
  • 1970-01-01
  • 2019-06-09
  • 2019-10-23
  • 2018-12-20
相关资源
最近更新 更多