Home > Software design >  return the answer to another promise file
return the answer to another promise file

Time:12-23

I have an isolated scene. And there is a promise in a separate file. But my scene does not want to wait for an answer. And continue to work. And continues to run, how do I make it wait for an answer, and continued to work
file: a

async function apiExchangerate(country, amount) {    
    return new Promise(function (resolve, reject) {
        axios.get(``, {
            headers: { "Accept-Encoding": "gzip,deflate,compress" },
            }).then(
            (response) => {
                var result = String(response.data.result).replace(/\..*/, '');
                console.log('Processing Request');
                resolve(result);
            },
                (error) => {
                reject(error);
            }
        );
    });
}

module.exports = apiExchangerate

file: b

let request_currency = await apiExchangerate(country,amount) // you have to wait for a response, and then continue the work

I want my function to wait for a response and continue executing the script. On the Internet, I have not found an answer to my question.


P.s it doesn't work - What is the explicit promise construction antipattern and how do I avoid it?

CodePudding user response:

You're wrapping Promises in Promises for no real reason. One of the reasons why this is an anti-pattern is because it's very easy to get confused by that and to mis-handle resolving/rejecting those Promises.

(My guess is that somewhere you're returning a Promise which resolves to... a Promise. And you're not double-awaiting it so you never resolve the actual Promise.)

Don't over-design it. Simplify the function. axios.get already returns a Promise, and the function is already async, use those:

async function apiExchangerate(country, amount) {
  let response = await axios.get(``, {  headers: { "Accept-Encoding": "gzip,deflate,compress" } });
  let result = String(response.data.result).replace(/\..*/, '');
  console.log('Processing Request');
  return result;
}

Then what you have is a simple async function which will internally await its own operations. And you can await that function:

let request_currency = await apiExchangerate(country, amount);
  • Related