[Vuejs]-Why i need to resolve a response in promise

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 throwing 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.

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.

Leave a comment