I am not going to talk about generator functions or Promises or the Fetch API in this article, but you can read for more information in the links I attached.
The following code snippet is basically what co package does where you can easily do asynchronous calls in a synchronous way. (the key difference here is co can deal with not only Promises, but here we just wanted to work with them, not like e.g. thunks, which co can handle).
Enough with the chit-chat, let's see some code!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
magic(function*() { | |
const uri = 'http://date.jsontest.com/'; | |
const response = yield fetch(uri); | |
const date = yield response.json(); | |
const time = date.time; | |
console.log('time: ', time); | |
}); | |
function magic(generator) { | |
const iterator = generator(); | |
const iteration = iterator.next(); | |
console.log('iteration: ', iteration); | |
const promise = iteration.value; | |
promise.then(response => { | |
console.log('response: ', response); | |
const anotherIterator = iterator.next(response); | |
const anotherPromise = anotherIterator.value; | |
anotherPromise.then(date=> iterator.next(date)); | |
}); | |
} |
Let's see what is happening here (click on "Next" and "Prev" to follow the steps of the control flow)
I think this whole topic is more about to move on to the next generation asynchron call methodology, which is called async-await and thus it is a needed step to be able to build that kind of behaviour.
BTW it's fun to have a look at what an ES6 transpiler is doing with this code-snippet, go on and try it here: https://babeljs.io/repl/
In summary I think we achieved a good (not great) way of handling asynchronous calls with a "synchron-like" feeling.