首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >nodejs使request-promise response可供进一步处理

nodejs使request-promise response可供进一步处理
EN

Stack Overflow用户
提问于 2020-05-08 04:33:30
回答 3查看 198关注 0票数 1

我想使用request-promise模块,并对响应体做一些事情。但是,我无法使响应在请求-承诺范围之外可用。

代码语言:javascript
复制
var rp = require('request-promise');

rp('http://www.google.com')
    .then(function (response) {
        let variable = response;
    })
    .catch(function (err) {
        // rejected
});

console.log(variable); // this will not work right? then, how to make it work in easy way?

谢谢你的帮助。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-05-08 04:39:05

该进程将异步工作,因此您的变量将始终为undefined,否则如果您在异步函数中声明它,它可能会抛出错误。

最好的方法是使用async await

代码语言:javascript
复制
var rp = require('request-promise');
async function getData()
{

let variable=await rp("http://www.google.com");
console.log(variable) // do anything with your variable
}


getData();

你想看看this

票数 0
EN

Stack Overflow用户

发布于 2020-05-08 04:43:17

3个选项供您选择。

示例1

代码语言:javascript
复制
const rp = require("request-promise");

rp("http://www.google.com")
  .then(res => {
    // you can use response here
  })
  .catch(e => console.log(e));

示例2

代码语言:javascript
复制
const rp = require("request-promise");

rp("http://www.google.com")
  .then(res => restOfMyCode(res))
  .catch(e => console.log(e));

const restOfMyCode = result => {
  console.log(result);
};

示例3

代码语言:javascript
复制
const rp = require("request-promise");

(async () => {
  try {
    const result = await rp("http://www.google.com");
    console.log(result);
  } catch (e) {
    console.log(e);
  }
  console.log(result)
})();
票数 0
EN

Stack Overflow用户

发布于 2020-05-08 05:19:44

感谢你们两位,你们启发了我的最终解决方案,目前看起来是这样的:

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

(async () => {

    var data = await getData();
    console.log(JSON.stringify(data, null, 2));     


    async function getData() {
            var options = {
                uri: 'https://www.google.com',
                json: true
            };
            var variable=await rp(options);
            return variable; // do anything with your variable
    }

}
) ();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61667238

复制
相关文章

相似问题

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