1

Would like to call configuration function defined at file B.js from File A.ts and set the return object in a config variable.

However I could not access the correct value for the config var or var x which are both reside outside of the 'then' function.

i could get the correct value inside the 'then' function, but not outside the 'then' function.

Code in A.tx

import {configuration} from "../../B";
var x = configuration("typeA").then(function(data){
        console.log("inside then fct: "+ JSON.stringify(data));
        config=data;
        return (data);
})
console.log("config"+JSON.stringify(config));
console.log("outside then fct: "+ JSON.stringify(x));

Code in B.js

exports.configuration = function (type) {
  return new Promise(function (resolve, reject) {
    var url = '/api/code/configuration/' + type;

    c.makeRequest('get', url)
    .then(function (data) {
       console.log("confi: "+JSON.stringify(data));
       resolve(data);
    })
    .catch(function (error) {
       reject(error);
    });
 });
};
noob
  • 45
  • 3
  • 11
  • Either put all the logic that depends on the asynchronous info inside the `.then` or `await` the Promise, there's not really any other decent way – CertainPerformance Jan 08 '19 at 06:19
  • i have tried various solution like resolve(data) but could not get the result outside of the then function – noob Jan 08 '19 at 06:21
  • tried your suggestion, var x = await configuration("typeA").then(function(data){ return (data); }) finally works for the code after that. Thanks for your input. – noob Jan 08 '19 at 06:25
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Jan 08 '19 at 06:44

0 Answers0