Resolve/Reject play role in javascript?

Asked

Viewed 116 times

8

As mentioned in the title, the resolve and Reject of a Promise already "make paper" of Return or yes (depending on the occasion) I need to use the Return?

Explaining with code, I could do these two ways:

//Retorna os ids dos produtos da aplicação!
function getProducts() {
    return new Promise(function (resolve, reject) {
        fetch("/api/catalog_system/pub/products/search?fq=productId:" + dataLayer[0].productId).then(function (response) {
            return response.json()
        }).then(function (res) {
            if (!res || res.length <= 0) resolve(null)
            else resolve([dataLayer[0].productId, res[0]["Compre Junto"][0]])
        }).catch(function (error) {
            reject(error);
        })
    })
}

//Retorna os ids dos produtos da aplicação!
function getProducts() {
    return new Promise(function (resolve, reject) {
        fetch("/api/catalog_system/pub/products/search?fq=productId:" + dataLayer[0].productId).then(function (response) {
            return response.json()
        }).then(function (res) {
            if (!res || res.length <= 0) return resolve(null)
            else return resolve([dataLayer[0].productId, res[0]["Compre Junto"][0]])
        }).catch(function (error) {
            return reject(error);
        })
    })
}

The two work, however, I don’t know if I should use Return or not, if it would influence anything... Can someone explain?

Thank you!

1 answer

1

The only difference is that when you use Return in the resolve/Reject you inhibit the execution of the other codes below the resolve/Reject call within the Promises body.

See the example below:

function promises1(param){
  return new Promise(function(resolve, reject) {
      if(param){
         resolve('ok - promises1');
         console.log("execução continuada após resolver promises1");
      }else{
        reject('erro - promises1');
      }
  })
}

function promises2(param){
  return new Promise(function(resolve, reject) {
      if(param){
        return resolve('ok - promises2');
         
         console.log("execução não continuada após resolver promises2");
      }else{
        reject('erro - promises2');
      }
  })
}

 promises1(true)
   .then(function(mensagem){
      console.log(mensagem)
   })
   .catch(function(mensagem){
      console.log(mensagem)
   });
   
promises2(true)
   .then(function(mensagem){
      console.log(mensagem)
   })
   .catch(function(mensagem){
      console.log(mensagem)
   });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.