How to Smartly Store the Final Results of Promise in a Variable in javascript

Asked 2 years ago, Updated 2 years ago, 128 views

aPromise.then(function taskA(value){
  // task A ~ some kind of action ~
}).then(function taskB(value){
  // task B
  // The value of taskB is the final result.
  // I want to store the value of taskB for this final result.
}).catch(function onRejected(error){
    console.log(error);
});

I wrote an example code.
I tried and tried because I wanted to store the value of task B here.
The result is the code I wrote below.

var result='Variable result with final result';
aPromise.then(function taskA(value){
  // task A ~ some kind of action ~
}).then(function taskB(value){
  // task B 
  // I want to store the value here.
  result=value;
}).catch(function onRejected(error){
    console.log(error);
});

I'm a beginner in programming, and I'm not confident. I was wondering if this is a smart way.

If you don't mind, please reply.

javascript promise

2022-09-30 20:12

2 Answers

I think you would like to use the calculated values (result, AJAX acquisition values, etc.) in other modules (such as DOM operation).
Considering the dangers of global variables and the difficulty of timing adjustment, it is desirable to write it to complete within then.
Errors that occur during processing with result can also be handled within the catch, so the processing will be consolidated into one place and happiness will increase.

//----otherModule.js----
OtherModule.otherModuleFunction1_UseTaskB_Result=function(result){
    // I will do my best to solidify the processing part that uses the result and make it into a module.
    // It is safe to pass the calculated value of taskB through the argument.
};
OtherModule.otherModuleFunction2_UseTaskB_Result=function(result){
    // moderately divided
}

// ----promiseHandle.js----
aPromise.then(function taskA(resolvedValue){
  // task A ~ some kind of action ~
  return doSomething1 (resolvedValue);
}).then(function taskB(valueFromTaskA){
  var result=doSomething2(valueFromTaskA);
  OtherModule.otherModuleFunction1_UseTaskB_Result(result);
  OtherModule.otherModuleFunction2_UseTaskB_Result(result);
}).catch(function onRejected(error){
  console.log(error);
});

If you use more than one Promise, I think it would be good to use Promise.all, which will meet everyone's completion.


2022-09-30 20:12

Recently, I think it's smart to use async wait.

async function myFunction(aPromise){
  try{
    // If taskA() also returns Promise, 'wait taskA(...)'.
    let result=taskB(taskA(await aPromise));
    ...
  } catch(error){
    console.log(error);
  }
}


2022-09-30 20:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.