I'm try to understand how .then()
function can get two arguments like this.
const promise = doSomething();
const promise2 = promise.then(successCallback, failureCallback);
or
const promise2 = doSomething().then(successCallback, failureCallback);
but I want to convert two arguments .then()
to async/await
like this.
const result = await doSomething()
// execute successCallback if success.
// execute failureCallback if failure.
This is the website that I'm trying to learn.
Mozilla Firefox Developer : Using promise
Mozilla Firefox Developer : Promise Chaining
CodePudding user response:
When you await
a promise that resolves, you directly get its value:
const result = await doSomething();
When you await
a promise that rejects, it throws an exception that you can either let propagate back to the caller of the current function (as a rejected promise since all async
functions return a promise and async functions turn uncaught exceptions into a rejected promise) or you can catch it yourself locally with try/catch
.
try {
const result = await doSomething();
} catch(e) {
console.log(e);
}
It is not recommended to map promises to callbacks. It's much better to just return the promise and let the caller deal with the promise directly either with .then()
or await
.
If you really needed to map await
to successCallback
and failureCallback
, then you would do this:
try {
const result = await doSomething();
successCallback(result);
} catch(e) {
failureCallback(e);
}
But, at that point, you may as well just use .then()
since it's less code:
doSomething().then(successCallback, failureCallback);
But, as I said earlier, you generally don't want to map promises into callbacks. It's more likely that you wrap older callback-based APIs into promises so you can use promises for all your control-flow and not mix/match models (which tends to seriously complicate good error handling when you mix models).
CodePudding user response:
You can wrap the doSomething in a try catch method to capture the success and fail like this.
try {
const result = await doSomething()
} catch (err) {
console.log(err.message)
}
CodePudding user response:
Use try...catch
try {
const result = await doSomething()
// success
successCallback();
}
catch (e) {
// error
failureCallback();