简体   繁体   中英

Webpack -API I can't pass the data to the index.js

I'm trying to get the data from an api request I'm doing, I'm using Webpack, one file is making the get request and I want to use the data on the index.js, but i can't get it. This is the code with the get request:

request= require('superagent/lib/client')
module.exports=

request.get("http://www.omdbapi.com/?s=Batman&page=2").then(function 
(response) {
return response

how can i get the response in the index.js?

Thanks

Basically the thing is you are dealing with promises, which by nature are async and you need to wait until the request is complete in order to have the text from the request, in this case what you can do is use promises and pass a callback to execute when the request is completed such as:

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

Or you can use async and 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() );

Which is supported currently on:

  • Chrome 55
  • Firefox 52
  • Opera 42
  • Safari 10
  • Node 7.8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM