Is there any way to get out of the promise like a break?

Asked 2 years ago, Updated 2 years ago, 38 views

Is there a way to escape halfway while proceeding with Promise in Javascript (node express)? I want to get the value from db and if there is no result, I want to get the value again using another sql.
 The process of reading from the first db is called read_data_first, parse_data_first to parse the read datas value and return it to the result value, and in the case of writing another sql sentence, read_data_second, parse_data_second If read_data_first succeeds when creating logic with prompt, I want to run only parse_data_first, and if it fails, I want to run read_data_second and parse_data_second. 
However, if read_data_first is successful, the parse_data_second below will be executed differently than I intended.

// Send reject('not_exist') if there is no data in this function.

read_data_first() 

.then(parse_data_first)

.catch(
if(err.message===‘not_exist’){
    read_data_second();

}else{

    Next(err)// There could be a real error

})

.then(
parse_data_second();
)

.catch(
next(err);
)

'. Is there any way to completely end the promotion in the desired part? For example, if parse_data_first is completed, end the promise (if you return, it will only move on to the next time)

javascript node.js

2022-09-21 17:15

1 Answers

Originally, pramis are often used in atomic operations.

If you want to force it to end, Inside that function, There is a method of calling the through new Error ('reason') to force it to the catch function.

However, it is important to note that catch() is not used in the middle of enable After listing all the logics you want to cancel, you have to write them only at the end.

For example, There is a code as below.

promise
.then(func1)
.then(func2)// raise exception!!
.then(func3)
.catch(handle1)
.then(func4)
.then(func5);

If an exception occurs in func2,

func1 => Some code before the exception to func2 => handle1 => func4 => func5

It runs in order. The func3 is jumping.

Therefore, those that need to ensure atomic execution should be chained adjacent to enable, and exceptions for individual steps should be made at once by checking the types of error values predefined in one catch().

I am attaching the code that I tested.

const wait = new Promise((resolve, reject)=>{
  const duration = 1000 + Math.random() * 4000;    
  setTimeout(()=> {
    resolve(duration);
  }, }, duration);
});

wait.then(()=>{
  console.log('first');
})
.then(()=>{
  console.log('second');
  throw new Error('on second');
})
.then(()=>{
  console.log('third');
})
.then(()=>{
  console.log('fourth');
})
.catch((err)=>{
  console.log(err)
})
.then(()=>{
  console.log('fifth');
})
.then(()=>{
  console.log('sixth');
});


2022-09-21 17:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.