从回调设置全局变量

时间:2018-06-19 20:32:29

标签: node.js asynchronous node-modules

首先,我需要使用“请求”来获取数据,然后将响应添加到变量firstData中:

var request = require('request');
let firstData,otherData = '';
request({
    url: 'https://someurl.extension/get/data',
    method: "POST",
    json: true,
    body: {}
  },(error, response) => {
   firstData = response;
  })

然后我再次请求获取otherData的值:

request({
    url: 'https://someurl.extension/get/otherdata',
    method: "POST",
    json: true,
    body: {}
  },(error, response) => {
   otherData = response;
  })

然后用它们渲染它们 res.json({firstData,otherData}) 但什么都没有出现,因为异步无法做到这一点。有人说应该通过“回调”来完成,但是如果我需要发出5个或更多的请求怎么办?将有5个回调,并且代码不再漂亮。 有什么办法吗?还是有什么办法可以响应全局变量?在Reactjs中类似setState()的东西。 谢谢。

1 个答案:

答案 0 :(得分:3)

您可以承诺request或只使用request-promise,然后使用async/await

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

app.get('/some-route', async(req, res) => {
                      // ^^ Notice async keyword
    try {

        const firstData = await request({
            url: 'https://someurl.extension/get/data',
            method: "POST",
            json: true,
            body: {}
        });

        const otherData = await request({
            url: 'https://someurl.extension/get/otherdata',
            method: "POST",
            json: true,
            body: {}
        });

        res.json({
            firstData,
            otherData
        })

    } catch (e) {
        res.status(500);
        res.send('Error');
    }

});

如果可以并行执行请求(如果它们彼此不依赖),则可以使用Promise.all

const [firstData, secondData] = await Promise.all([
     request(/* first request options  */),
     request(/* second request options */)
]);
相关问题