1đ
Something thatâs worth mentioning is axios.post()
already returns a Promise
so you neednât wrap it in another promise.
This will work instead:
let promise = axios.post("https://httpbin.org/post", params, header)
.then(response => {
console.log(response);
return Object.assign({}, response.data);
});
// Later on...
promise.then(data => {
console.log('Request successful:', data);
}, err => {
console.log('Request failed:', err);
});
Constructing a new Promise
object is only necessary when you arenât chaining off an existing promise, like in this example:
function delay(duration) {
return new Promise(resolve => setTimeout(resolve, duration));
}
delay(1000).then(() => {
console.log('this code is delayed by 1s');
});
0đ
resolve()
does exactly what the name says: It resolves the promise returning the value inside the function call.
So if you have a promise and it is resolving with resolve('aaaaa')
, this means your promise will return a successful state with itâs value being âaaaaaâ.
You could also reject the promise. This would mean the call you did failed at some point. Analog to resolve()
, reject()
accepts a parameter that should be returned by the promise.
0đ
Promises have two arguments, resolve
and reject
, that are used to send a response back to the invoking code.
If your promise completed its code without errors, then you resolve()
it, by sending back the response (it can be whatever you want) and if it fails instead, you reject()
it, usually passing the error as parameter.
The parameter of the resolve function will be sent back to the invoking function, in the then callback, while the parameter of the reject function can be found in the catch callback.
For example
function myFunction(){
return new Promise((resolve, reject) => {
try{
/* Do some async calls here */
resolve(result); //Result is what you will find in "then"
}catch(e){
reject(e);
}
});
}
myFunction().then((response) => {
/* Your logic here*/
}).catch((err) => {
console.error(err);
}
You can think the resolve
as a return
in an asynchronous context, while the reject
is similar to throw
ing an exception that will be caught by the invoking code.
So resolve(myVariable)
will return myVariable
to the code that called the promise function, while resolve('aaa')
will always return âaaaâ to the invoking code.
- [Vuejs]-VueFire watch for empty array property
- [Vuejs]-Best practise vue.js frontend and python backend
0đ
All it will do is call the success callback resolve
with the argument "aaaa"
instead of its original value.
Letâs say you pass the callback function console.log
. If the promise resolves, i.e. is successful, then the callback will be called with the passed argument (console.log("aaaa")
)
If it doesnât resolve â if itâs unsuccessful â then the reject
callback will be called as per your .catch()
statement.