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

Already subscribed? Sign In

Autoplay

    Use the await Operator with Any Thenable

    Marius SchulzMarius Schulz

    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.

    javascriptJavaScript
    Code

    Code

    Become a Member to view code

    You must be a 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
    Transcript

    Transcript

    00:00 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.

    00:19 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.

    00:27 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.

    00:41 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.

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

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

    01:20 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.

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

    Discuss

    Discuss