[英]Webpack -API I can't pass the data to the index.js
我正在尝试从正在执行的api请求中获取数据,我正在使用Webpack,一个文件正在发出get请求,并且我想使用index.js上的数据,但我无法获取它。 这是带有get请求的代码:
request= require('superagent/lib/client')
module.exports=
request.get("http://www.omdbapi.com/?s=Batman&page=2").then(function
(response) {
return response
我如何在index.js中获得响应?
谢谢
基本上,您要处理的是Promise,它本质上是异步的,您需要等到请求完成才能从请求中获得文本,在这种情况下,您可以做的是使用Promise并将callback
给请求完成后执行,例如:
var request= require('superagent/lib/client')
module.exports = function request( onFinished, onError ){
request.get("http://www.omdbapi.com/?s=Batman&page=2")
.then( onFinished )
.catch( onError );
}
// Use file.js
makeRequest = require('path/file');
makeRequest(function(result){
console.log(result); // result from the request.
}, function( error ) {
console.log( 'There was an error' );
})
或者您可以使用async
和await
。
var request= require('superagent/lib/client')
module.exports = function async request( onFinished, onError ){
let response = '';
try {
response = await request.get("http://www.omdbapi.com/?s=Batman&page=2");
} catch ( e ) {
console.log( error );
}
return response;
}
// Use file.js
makeRequest = require('path/file');
console.log( makeRequest() );
当前受以下支持:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.