我想使用request-promise模块,并对响应体做一些事情。但是,我无法使响应在请求-承诺范围之外可用。
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?谢谢你的帮助。
发布于 2020-05-08 04:39:05
该进程将异步工作,因此您的变量将始终为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
发布于 2020-05-08 04:43:17
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)
})();发布于 2020-05-08 05:19:44
感谢你们两位,你们启发了我的最终解决方案,目前看起来是这样的:
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
}
}
) ();https://stackoverflow.com/questions/61667238
复制相似问题