简体   繁体   中英

Can't break promise chain with return

I've got a chained promise using .then() , the issues I am having is i'm getting Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client - I know why i'm getting it (there are 2 responses in the promise) however after doing lots of reading I can't figure out how to break the .then() callback - i've been trying to use return , however it keeps running to the next chain in the promise.

How do I stop the chain at the first res - response, when the checkResult if statement is false ?

Promise Chain

  await query1()
    .then((checkResult) => {
      if (!checkResult) {
        return res.status(200)
      }
    })
    .then(() => query2())
    .then((result) => {
      return res.status(201).json({ result: result, status: 201 });
    })
    .catch((err) => console.error(`Error occurred: ${err}`));

Query 1 Example

  async function query1(){
    return false
    }

Just use async/await which simplifies control flow issues like these:

  try {
    let checkResult = await query1();
    if (!checkResult) {
      return res.status(200);
    }
    let result = await query2();
    return res.status(201).json({ result: result, status: 201 });
  } catch(err) {
    console.error(`Error occurred: ${err}`));
  }

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