首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在变量中返回请求函数的正文

在变量中返回请求函数的正文
EN

Stack Overflow用户
提问于 2019-11-29 19:43:18
回答 2查看 322关注 0票数 0

我的节点后端有一个端点,在这个端点中,我需要从本地数据库中检索Adhoc集合中的每一项的_id以及一个Numer值,我需要从对象数组中的request()函数体中计算出该值。对象将如下所示

代码语言:javascript
运行
复制
{id: "id", sum: 3}

为此,我需要使用for循环遍历Adhocs,并请求每个Adhocs来获得sum值,并且我需要能够在获得所有值之前存储这些值,并将数组res.send()到前端。我在变量中存储sum值时遇到问题。我已经在下面提供了请求的代码。

代码语言:javascript
运行
复制
let theSum = request(options, function (error, response, body) {
     if (error) throw new Error(error);
     console.log(
        'Response: ' + response.statusCode + ' ' + response.statusMessage
     );
     let bodyy = JSON.parse(body);
     let sum = bodyy.fields.timetracking.originalEstimateSeconds / 3600 * theRate;
     return sum;
  });

我知道这是错误的,因为return语句是针对请求函数中的函数的,所以它不会将sum返回给我的变量。添加另一个回调函数基本上是相同的场景。谁有什么建议,我可以存储请求函数的值,以便我可以进行进一步的调用?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-11-29 22:43:30

我找到了一个非常适合我的答案。我没有尝试上面Terry的答案,但我想这也行得通,因为它使用Promise和我一样好。我所做的是在一个函数中,我将请求调用包装在一个带有回调的Promise中,该回调将被返回。代码如下:

代码语言:javascript
运行
复制
function asyncRequest (url) {

   return new Promise (function (resolve, reject) {

   var options = {

        url: 'http://localhost:8080/rest/' + url,

        auth: { username: 'username', password: 'password' },

        headers: {
            'Accept': 'application/json'
        }
   }

   request(options, function (err, response, body) {
       if (err) reject(err);
       resolve(JSON.parse(body))
   });
   })
}

当我想检索一些东西时,我只需要这样的东西:

代码语言:javascript
运行
复制
let json = await asyncRequest('agile/1.0/issue/'+ adhoc[u].jIssue);

该变量包含请求函数体,我可以使用它。

票数 2
EN

Stack Overflow用户

发布于 2019-11-29 20:59:54

你可以使用async和await以及request-promise-native来遍历你的对象并得到你想要的结果列表。

您可以在express.get( )中调用readEstimates函数。只要处理程序是异步的(或者您可以使用readEstimates().then(..))。

现在,我们将在readEstimates调用周围包装一个错误处理程序,因为这可能会抛出错误。

例如:

代码语言:javascript
运行
复制
const rp = require('request-promise-native');

async function readEstimates() {
    const sumList = [];
    for(const adhoc of adhocList) {
        // Set your options here, e.g. url for each request.. by setting json to true we don't need to JSON.parse the body.
        let options = { url: SOME_URL, json: true, resolveWithFullResponse: true };
        let response = await rp(options);
        console.log('Response: ' + response.statusCode + ' ' + response.statusMessage);
        const sum = response.body.fields.timetracking.originalEstimateSeconds / 3600 * theRate;
        sumList.push(sum);
    }
    return sumList;
}

async function testReadEstimates() {
    try {
        const sumList = await readEstimates();
        console.log("Sumlist:", sumList);
    } catch (error) {
        console.error("testReadEstimates: An error has occurred:", error);
    }
}



testReadEstimates();

您还可以在快速路由中使用readEstimates:

代码语言:javascript
运行
复制
app.get('/', async (req, res) => {
    try {
        const sumList = await readEstimates();
        res.json({sumList}); // Send the list to the client.
    } catch (error) {
        console.error("/: An error has occurred:", error);
        res.status(500).send("an error has occurred");
    }
})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59104137

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档