Email Subscription Form

Saturday, June 6, 2020

Adventures in Node: Promises

Have you ever written an automated UI test that uses Javascript, and when you went to assert on a response, you got Promise {pending} instead of what you were expecting?  This really frustrated me when I first encountered it!  A developer I was working with explained that this is because Javascript processes commands asynchronously through the use of promises.  I sort of understood what he meant, so I tried to work with it as best I could, but I didn't really get it.

As I mentioned in this post, I've been taking a really awesome course on Node.js.  It's much more extensive than any programming language course I've ever taken, even the ones I took in college.  So I'm starting to understand Node concepts more clearly, and one of those concepts is promises!  In this post I'll explain why Javascript and Node need promises and show an example of how they work.


Javascript needs promises because it is a single-threaded language, meaning it can only do one thing at a time.  If we had a program where we needed to do three things, such as make an http request, alphabetize a list, and update a record in a database, we wouldn't want to have to wait around for each of those tasks to finish before we went on to the next one, because our program would be very slow!  So Javascript is designed to be asynchronous- it can start a task, and then while it's waiting for that task to complete, it can start the next task.

Our program with three things might actually run like this:
start the http request
start alphabetizing the list
start updating the record in the database
finish alphabetizing the list
finish updating the record in the database
finish the http request

The way that Javascript and Node manage this is through the use of promises.  Let's take a look at a promise:

const sumChecker = new Promise((resolve, reject) => {
     if (a+b==c) {
          resolve('You are correct!)
     }
     else {
          reject('Sorry, your math is wrong.')
     }
}

This function called sumChecker is a promise.  It's going to have two possible results: resolve and reject.  If the sum is correct, it resolves the promise, and if it's incorrect, it rejects it.  All promises behave in this way; there will be an option to resolve the promise and an option to reject the promise.

When the promise is called, either resolve or reject will be returned; you can't ever return both.  Let's look at an example of calling the promise:

sumChecker.then((result) => {
     console.log('Success!', result)
}).catch((error) => {
     console.log('Error!', error)
})

The result that is returned from calling the promise will either be resolve or reject.  If the result is resolve, then the program knows to continue and will return the resolve message.  If the result is reject, then the program knows to throw an error and will return the reject message.

You can try this for yourself if you have Node installed!  Simply copy the promise and the call and paste them into your favorite code editor.  Then at the beginning of the file, add these lines:

var a = 1
var b = 2
var c = 3

Save the file with the name myfile.js, navigate in the command line to the file's location, and run the file with the command node myfile.js.  You should see this response: Success! You are correct!

If you make a change to the c variable and set it to 4, save and run the command again, you'll see this response: Error! Sorry, your math is wrong.

Let's put a log statement in between the promise and the call to the promise that looks like this: console.log(sumChecker), so we can see the state of sumChecker before we've called it. If we change the value of c back to 3 so we'll get a positive result, save the file, and run the program with node myfile.js now, we'll get the result Promise { 'You are correct!'} in addition to the response we got earlier.  That seems easy!  But the reason why we can get the promise resolved so quickly is because the sumChecker promise executes really fast.  Let's see what happens if we make the sumChecker work more slowly, like a real promise would.

Update the sumChecker promise to look like this:

const sumChecker = new Promise((resolve, reject) => {
     if (a+b==c) {
          setTimeout(() => {
               resolve('You are correct!)
          }, 2000)
     }
     else {
          reject('Sorry, your math is wrong.')
     }
}

All we're doing here is adding a two-second timeout to the resolved promise.  Save the file, and run the program again with node myfile.js.  This time you'll first get the result Promise { <pending> }, and after two seconds, you'll get the result Success! You are correct!  

Now it should be clear why you get Promise { <pending> } when you are making Javascript or Node calls.  It's because the promise hasn't completed yet.  This is why we use the .then() command.  We wait for the response to the call to come back, then we do something with the response.  If we're writing a test, at that point we can assert on our result.

I hope you'll take the time to try running this file with Node, because there's nothing quite like doing hands-on work to generate understanding.  You can try changing the variables or any of the response messages to get a feel for how it's working.  Here's the final version of the file if you'd like to copy and paste it:

var a = 1
var b = 2
var c = 3

const sumChecker = new Promise((resolve, reject) => {
    if (a+b==c) {
        setTimeout(() => {
            resolve('You are correct!')
        }, 2000)
    }
    else {
        reject('Sorry, your math is wrong.')
    }
})

console.log(sumChecker)

sumChecker.then((result) => {
    console.log('Success!', result)
}).catch((error) => {
    console.log('Error!', error)
})

Enjoy your new-found understanding of promises!

24 comments:

  1. Hey Guys !

    USA Fresh & Verified SSN Leads with DL Number AVAILABLE with 99.9% connectivity
    All Leads have genuine & valid information

    **HEADERS IN LEADS**
    First Name | Last Name | SSN | Dob | DL Number | Address | City | State | Zip | Phone Number | Account Number | Bank Name | Employee Details | IP Address

    *Price for SSN lead $2
    *You can ask for sample before any deal
    *If anyone buy in bulk, we can negotiate
    *Sampling is just for serious buyers

    ==>ACTIVE, FRESH CC & CVV FULLZ AVAILABLE<==
    ->$5 PER EACH

    ->Hope for the long term deal
    ->Interested buyers will be welcome

    **Contact 24/7**
    Whatsapp > +923172721122
    Email > leads.sellers1212@gmail.com
    Telegram > @leadsupplier
    ICQ > 752822040

    ReplyDelete
    Replies



    1. I highly recommend a particular trader to everyone looking for forex, crypto and Binary trader. In this period of economic crisis, Instead of going for a loan I decided to invest in Forex/bitcoins trading with Barry Silbert, After reading a lot of good reviews about him . I am glad to tell you that he is the only legit trader I know. I now make more than $6,099 a week. He can help you earn formidable profit weekly  with his good trading strategies weekly, For more details, Contact Mr Barry Silbert on Email: Barrysilbert540@gmail .com  
      WhatsApp: +447508298691  


      Delete

  2. The website loading pace is incredible.webcare360.com It seems t
    hat you’re doing any distinctive trick. Also,

    ReplyDelete
  3. Hello everyone, Are you into trading or just wish to give it a try, please becareful on the platform you choose to invest on and the manager you choose to manage your account because that’s where failure starts from be wise. After reading so much comment i had to give trading tips a try, I have to come to the conclusion that binary options pays massively but the masses has refused to show us the right way to earn That’s why I have to give trading tips the accolades because they have been so helpful to traders . For a free masterclass strategy kindly contact (paytondyian699@gmail.com) for a free masterclass strategy. He'll give you a free tutors on how you can earn and recover your losses in trading for free..

    ReplyDelete
  4. **SELLING SSN+DOB FULLZ**

    CONTACT
    Telegram > @leadsupplier
    ICQ > 752822040
    Email > leads.sellers1212@gmail.com

    >>1$ each without DL/ID number
    >>2$ each with DL
    >>5$ each for premium (also included relative info)

    *Will reduce price if buying in bulk
    *Hope for a long term business

    FORMAT OF LEADS/FULLZ/PROS

    ->FULL NAME
    ->SSN
    ->DATE OF BIRTH
    ->DRIVING LICENSE NUMBER WITH EXPIRY DATE
    ->COMPLETE ADDRESS
    ->PHONE NUMBER, EMAIL, I.P ADDRESS
    ->EMPLOYMENT DETAILS
    ->REALTIONSHIP DETAILS
    ->MORTGAGE INFO
    ->BANK ACCOUNT DETAILS

    >Fresh Leads for tax returns & w-2 form filling
    >Payment mode BTC, ETH, LTC, PayPal, USDT & PERFECT MONEY

    ''OTHER GADGETS PROVIDING''

    >SSN+DOB Fullz
    >CC with CVV
    >Photo ID's
    >Dead Fullz
    >Spamming Tutorials
    >Carding Tutorials
    >Hacking Tutorials
    >SMTP Linux Root
    >DUMPS with pins track 1 and 2
    >Sock Tools
    >Server I.P's
    >HQ Emails with passwords

    Email > leads.sellers1212@gmail.com
    Telegram > @leadsupplier
    ICQ > 752822040

    THANK YOU

    ReplyDelete
  5. Do you need Personal Finance?
    Business Cash Finance?
    Unsecured Finance
    Fast and Simple Finance?
    Quick Application Process?
    Finance. Services Rendered include,
    *Debt Consolidation Finance
    *Business Finance Services
    *Personal Finance services Help
    contact us today and get the best lending service
    personal cash business cash just email us below
    Contact Us: financialserviceoffer876@gmail.com
    call or add us on what's app +918929509036

    ReplyDelete
  6. BE SMART AND BECOME RICH IN LESS THAN 3DAYS....It all depends on how fast 
    you can be to get the new PROGRAMMED blank ATM card that is capable of
    hacking into any ATM machine,anywhere in the world. I got to know about 
    this BLANK ATM CARD when I was searching for job online about a month 
    ago..It has really changed my life for good and now I can say I'm rich and 
    I can never be poor again. The least money I get in a day with it is about 
    $50,000.(fifty thousand USD) Every now and then I keeping pumping money 
    into my account. Though is illegal,there is no risk of being caught 
    ,because it has been programmed in such a way that it is not traceable,it 
    also has a technique that makes it impossible for the CCTVs to detect 
    you..For details on how to get yours today, email the hackers on : (
    atmmachinehackers1@gmail.com ). Tell your 
    loved once too, and start to live large. That's the simple testimony of how 
    my life changed for good...Love you all ...the email address again is ;
    atmmachinehackers1@gmail.com

    ReplyDelete
  7. The Content You Shared With Us Is Excellent & Extraordinary Useful to all Aspirants Thanks For Sharing With Us!
    Software Testing Classes in Pune thanks .

    ReplyDelete
  8. Hi Guy's

    Fresh & valid spammed USA SSN+Dob Leads with DL available in bulk.

    >>1$ each SSN+DOB
    >>2$ each with SSN+DOB+DL
    >>5$ each for premium (also included relative info)

    Prices are negotiable in bulk order
    Serious buyer contact me no time wasters please
    Bulk order will be preferable

    CONTACT
    Telegram > @leadsupplier
    ICQ > 752822040
    Email > leads.sellers1212@gmail.com

    OTHER STUFF YOU CAN GET

    SSN+DOB Fullz
    CC's with CVV's (vbv & non-vbv)
    USA Photo ID'S (Front & back)

    All type of tutorials available
    (Carding, spamming, hacking, scam page, Cash outs, dumps cash outs)

    SMTP Linux Root
    DUMPS with pins track 1 and 2
    Socks, rdp's, vpn's
    Server I.P's
    HQ Emails with passwords

    Looking for long term business
    For trust full vendor, feel free to contact

    CONTACT
    Telegram > @leadsupplier
    ICQ > 752822040
    Email > leads.sellers1212@gmail.com

    ReplyDelete
  9. Integrated Assessment Services (IAS)is an authorized ISO certification body with UQAS accreditation. This implies that IAS is approved to audit third party organisations and is responsible to issue various standards such as ( including ISO 9001, ISO 14001,ISO 22000:2018, CE Marking, RoHS Certification, OHSAS 18001, ISO 22000/HACCP, ISO 27001 (ISMS), IATF 16949, ISO 13485 and SA8000). Visit iso germany

    ReplyDelete
  10. Do you need personal loan?
    Loan for your home improvements,
    Mortgage loan,
    Debt consolidation loan,
    Commercial loan,
    Education loan,
    Car loan,
    Loan for assets.
    financialserviceoffer876@gmail.com WhatsApp +918929509036

    ReplyDelete
  11. If you are also interested in seo company primelis then you are reading the right comment because it is very best company, I get a lot of help from here, I have got my work done from here and I will tell everyone that it will be the best. SEO work related to work.

    ReplyDelete
  12. You doing very nice work in this article. I really like it. Keep posting are going to be expecting your next article. Now it's time to avail solar energy for more information.

    ReplyDelete
  13. We <"https://financialforcesupport.com/"> FinancialForce support services provide start at $1800 per month.

    ReplyDelete
  14. When it comes to Table Lamps, you want something that is beautiful and functional. The Grayson Living line of table lamps has a wide range of styles and designs to choose from.

    ReplyDelete
  15. Copeland Furniture makes for nice storage too, so you don't have to spend time looking for what you need. The selection of Copeland bedroom furniture available at Grayson Home makes your bedroom look stunning and the Copeland living room furniture gives you plenty of space.

    ReplyDelete
  16. This comment has been removed by the author.

    ReplyDelete
  17. What's Up Everyone

    Fresh Databases available

    CC's CVV's SSN
    Pros High Credit Scores 700+
    Fullz/Leads with SSN+DOB+DL
    Dumps
    EIN Leads
    Bulk HQ Emails
    Office365 Emails & Logs

    >>>WA/Telegram +92 317 272 1122
    >>>ICQ 752822040
    >>>Skype/Wickr @peeterhacks
    >>>Email exploit dot tools4u at gmail dot com

    Quality Tools & Tutorials available for
    HACKING|SPAMMING|CARDING|SPYING|CLONING|CASH-OUTS|TRANSFERS

    Legit Fullz/Pros/Leads will be provided
    Bulk quantity also
    Invalid stuff will be replaced/No refund
    BTC & USDT payments mode
    Available 24/7

    Feel Free to contact Guy's

    ReplyDelete
  18. Learn about Healing Buddha's mission to empower clients with tools for self-care, enabling them to continue their healing journey.
    healingbuddha

    ReplyDelete
  19. Salesforce Service Cloud is about ensuring that businesses provide exceptional customer service. It's like having a virtual customer care team on hand 24 hours a day, seven days a week. Salesforce Service Cloud Implementation can be a challenging yet rewarding experience, but it is important to streamline their customer service operations, improve their agent productivity, and ultimately enhance their overall customer experience.

    With Salesforce Service Cloud Implementation, you can easily assist your businesses to leverage the power of Salesforce to achieve your business goals. Request a free consultation with an AblyPro expert to learn how Salesforce Service Cloud may help your company improve customer service and drive higher retention rates!

    ReplyDelete
  20. Discover how art and business intersect in captivating ways with The Global Hues. Join us in celebrating creativity and innovation.

    theglobalhues

    ReplyDelete
  21. Recently purchased Click here services and highly recommend them to anyone needing professional work done! The quality exceeded my expectations and the turnaround time was impressive. A fantastic investment for anyone looking to elevate their brand or project.

    ReplyDelete
  22. When it comes to Best IVF in Delhi stands out as a hub of excellence. The delhi boasts of renowned Nandi IVF clinics that are known for their high success rates and patient satisfaction. These clinics combine cutting-edge technology with the expertise of experienced fertility specialists to provide the best possible outcomes for couples struggling with infertility.

    In Delhi, you can expect world-class facilities and a compassionate approach to fertility care. The clinics prioritize patient comfort and convenience, offering a range of services under one roof. From initial consultations and diagnostic tests to the actual IVF procedure and post-treatment care, everything is meticulously planned and executed to ensure the highest level of success.

    So, if you are looking for the best IVF services in Delhi, rest assured that you will receive top-quality treatment and care from the moment you step into one of these esteemed clinic.

    ReplyDelete

New Blog Location!

I've moved!  I've really enjoyed using Blogger for my blog, but it didn't integrate with my website in the way I wanted.  So I&#...