xcode
xcode

Reputation: 1717

How to Export Data Outside .then() Block (SuperAgent Library)?

I have two files on my Nodejs project that depends on each other. I use a simple library called SuperAgent (I need it)

SuperAgent Library Links

in file1.js

const file2 = require('./file2');

let callMe = async (x) => {
  const resData = await file2.getNow(x);
  console.log(resData);
};
callMe('Header Data');

while in file2

const request = require('superagent');

module.exports = {
  getNow: (x) => {
    // Here I use simple SuperAgent
    return request
      .get('https://loremipsum.com')
      .set({
        Header: `${x}`,
      })
      .then(function (res) {
        // I want res to be pass to resData variable on file1
      });
  }
};

I want res to be pass to resData variable on file1.

I already tried many different things here, assigning to variable or returning a value, but it doesn't work so far, and resData keep giving undefined value. How to solve this problem?

Upvotes: 1

Views: 134

Answers (1)

Roman Grinev
Roman Grinev

Reputation: 1037

Is following example works for you?

file1

const file2 = require('./file2');

let callMe = async (x) => {
  const resData = file2.getNow(x).then(function(resData){
      console.log(resData);
  })
};
callMe('Header Data');

file2

const request = require('superagent');

module.exports = {
  getNow: (x) => {
// Here I use simple SuperAgent
return request
  .get('https://loremipsum.com')
  .set({
    Header: `${x}`,
  })
  .then(function (res) {
      // I want res to be pass to resData variable on file1
      return Promise.resolve(res)
  });
  }
};

Upvotes: 1

Related Questions