#Convert callback to promise using .catch

7 messages · Page 1 of 1 (latest)

trim crane
#

Is this just an exercise is using callbacks/Promises? Because there's nothing asynchronous happening in printFullName that would warrant needing a callback or Promise.

digital shadow
#

I am trying to make a resolve log out when the user provides the argument but if the user does not I want to run a reject

#

const printFullName = (firstName, callback) => {
if (!firstName) return callback('No first name provided.')

    const fullName = `${firstName} Doe`
    return callback(fullName)
  }

  function display(s) {
    document.getElementById('demo').innerHTML += s + '<br>'
  }

  let myPromise = new Promise(function (myResolve, myReject) {
    setTimeout(function () {
      myResolve(printFullName('John', display))
    }, 10)
    setTimeout(function () {
      myReject('Please enter full name')
    })
  })

  myPromise.then(function (value) {
    document.getElementById('demo').innerHTML = value
  })
#

this is what I was able to do so far

#

I'm basically trying to make the myReject run if the user does not provide their firstName inside of the printFullName() function

trim crane
#

I guess I still don't understand why you're taking this approach, since the code you're running isn't doing anything asynchronous. But if it's just an exercise to maybe simulate an API call, try this:

    function printFullName(firstName) {
        return new Promise(function(resolve, reject) {
            setTimeout(function() {
                if (!firstName) {
                    return reject('No first name provided.');
                }
                
                const fullName = `${firstName} Doe`;
                return resolve(fullName);
            }, 2000); // simulate 2000ms round trip api call
        });
    }

    printFullName('Jane')
        .then(function(name) {
            console.log('Got name:', name);
        })
        .catch(function(err) {
            console.log('Got err:', err);
        });
digital shadow
#

Thats exactly what I was trying to do, what I was struggling on was the last part with using the .then and .catch