Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Use the await Operator with Any Thenable


    The await operator is not restricted to ES2015 promises. It can be used to await any thenable — that is, any object with a .then() method. This lesson illustrates how to await promises that have been created using a promise library.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    So far, we've used the await operator to wait for a promise. What happens if we try to await a non-promise value like this? The await operator will internally convert any non-promise value into a resolve promise, just as if we had written promise.resolve and then our value.

    If we now log this value to the console and then run our program, it shouldn't come as a surprise that we're going to see the value 42.

    The cool thing about this implicit promise creation is that it makes the await operator work with other promise implementations as well. Let's install the popular Bluebird promise library and see what that means.

    Let's go ahead and import Bluebird. Within our main function, we'll now use a Bluebird promise. We will say await bluebird.delay and then wait for two seconds. Let's also add two log statements so we can see what's going on.

    All right, let's see if this works. Working, 21, 22, and done. Perfect.

    What exactly is happening here? Bluebird.delay returns so-called called thenable, an object with a then method.

    Remember that we have this implicit promise.resolve call here. If the argument passed to promise.resolve has a then method, the return promise will follow that thenable and adopt its final state.

    In our case, the await expression pauses our asynchronous function for two seconds and then resumes it.