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.
[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.