nodejs 使请求承诺响应可用于进一步处理

nodejs make request-promise response available for further processing

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

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?

感谢您的帮助。

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

最好的方法是使用 async await

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

3 个选项供您选择。

示例 1


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

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

示例 2

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

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)
})();

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

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
    }

}
) ();