首页 > 解决方案 > 如何使用 Promise 仅在功能完成时发送响应

问题描述

如何仅在特定功能完成时发送响应。我尝试为此使用承诺,但这似乎不起作用。

let dealPromise = new Promise(function(resolve, reject){
for (let  i = 0;i < deals.length;i++) {
  let link = 'https://api.cortellis.com/api-ws/ws/rs/deals-v2/deal/' + deals[i] + '?fmt=json';
  let options = {
    method: 'GET',
    uri: link,
    auth: auth,
  };
  let constant = constants.collection('clarivate');

  request(options, function(error, response, body) {
    body = JSON.parse(body).dealRecordOutput;
    if (body.length === 0) {
      res.status(204).json({'data': []});
      next();
    }
    else {
      let type = body.Type;
      type_list.push(type);
      let status_val = body.Status;
      status_list.push(status_val);

      resp['type'] = type_list;
      resp['status'] = status_list;

       }
      });
    }
    resolve(resp);
  });

  dealPromise.then(function (result) {
    res.status(200).json({'data': result});
  });

还有其他方法可以解决这个问题吗?

标签: node.jspromise

解决方案


如果您切换到request-promise库来执行您的请求,那么它将为每个请求返回一个承诺,然后您可以使用Promise.all()它们来知道它们何时完成。

您的代码在许多主题上有点不完整,例如遇到空主体时该怎么办以及您希望如何构建最终result数据。因此,允许您填写这些详细信息,这里有一个适合您的通用结构:

const rp = require('request-promise');

let type_list = [], status_list = [];
Promise.all(deals.map(item => {
    let options = {
        method: 'GET',
        uri: 'https://api.cortellis.com/api-ws/ws/rs/deals-v2/deal/' + item + '?fmt=json',
        auth: auth
    };
    let constant = constants.collection('clarivate');
    return rp(options).then(body => {
        if (body.length !== 0) {
            try {
                let data = JSON.parse(body).dealRecordOutput;
                type_list.push(data.Type);
                status_list.push(data.Status)
            } catch(e) {
                // log and skip items with bad JSON
                console.log(e);
            }
        }
    });
})).then(() => {
    // all requests done here
    let result = {};
    // put code here to create result using type_list and status_list
    res.status(200).json({data: result});
}).catch(err => {
    // got an error in one of the requests
    console.log(err);
    res.sendStatus(500);
});

推荐阅读