'How to resolve or reject a promise from the result of another promise?

Really sorry if this has been answered, I've searched everywhere and can't find the exact problem I'm facing.

Take this as the example:

const fetchData = (email, password) => new Promise(async (resolve, reject) => {
    await axios.post('https://api.something.com', {
            email: email,
            password: password,
        },
        {            
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(res => {  
            cookie = res.headers['set-cookie'];
        })
        .catch(err => {
            return reject('Login failed');  
        });

    await axios.get('https://api.something.com', {
            headers: {
                'cookie': cookie
            }
        })
        .then(res => {  
            data = res;
        })
        .catch(err => {
            return reject('Failed to retrieve something'); 
        });    

    return resolve(data);
});

If the login credentials are incorrect, the 'Login failed' reject is sent but the script will keep on running and there will be an additional error message saying that cookie isn't set. I want to completely stop the script in the first catch.

I could use throw new Error('Login failed') and that would stop the script completely but I don't feel like that's the right answer and also because it makes me wonder what else could I use to resolve the promise (for other purposes) and still don't let the script continue running.

I'm also not interested in nesting functions, to avoid promise-callback christmas tree-like hell.

Am I making sense?



Solution 1:[1]

Because you use async/await you don't need create a new Promise and instead of then/catch use await and try/catch;

const fetchData = async (email, password) => {
  let cookie;
  try {
    const res = await axios.post(
      "https://api.something.com",
      {
        email,
        password
      },
      {
        headers: {
          "Content-Type": "application/json",
        },
      }
    );
    cookie = res.headers["set-cookie"];
  } catch (err) {
    throw new Error("Login failed");
  }

  let data;
  try {
    const res = await axios.get("https://api.something.com", {
      headers: {
        cookie
      },
    });
    data = res;
  } catch (err) {
    throw new Error("Failed to retrieve something");
  }

  return data;
};

If you want to use the Promise API instead of async/await you can chanin the promises: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#chaining

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1