我是nodejs和javascript的新手。我相信这是一个我不理解的范围问题。
给定此示例: ... ...
if (url == '/'){
var request = require('request');
var body_text = "";
request('http://www.google.com', function (error, response, body) {
console.log('error:', error);
console.log('statusCode:', response && response.statusCode);
console.log('body:', body);
body_text=body;
});
console.log('This is the body:', body_text)
//I need the value of body returned from the request here..
}
//OUTPUT
This is the body: undefined
我需要能够从响应中获取正文,然后进行一些操作,并且我不想在请求函数中执行所有实现。当然,如果我将日志行移动到:
request( function { //here })
它有效。但是我需要在请求之外以某种方式归还尸体。任何帮助将不胜感激。
你不能用回调来做到这一点,因为这会异步工作。
在 JS 中使用回调是很正常的。但是你可以用承诺做得更好。
您可以使用 request-promise-native 来执行 async/await 所需的操作。
async function requestFromClient(req, res) {
const request = require('request-promise-native');
const body_text = await request('http://www.google.com').catch((err) => {
// always use catches to log errors or you will be lost
})
if (!body_text) {
// sometimes you won't have a body and one of this case is when you get a request error
}
console.log('This is the body:', body_text)
//I need the value of body returned from the request here..
}
如您所见,您必须始终在函数作用域中才能在承诺中使用 async/await。
建议:
- 正确的 JS 方式
- ES6 功能线
- JS干净编码
- 更多最佳实践...
- 使用承诺