Reputation: 237
I'm new to node.js and the concept of callbacks. I have experience with Rails, PHP, etc. and now I'm learning node.js.
I want to create a simple Mail Client that uses the Google GMail API. The sample code is here: https://developers.google.com/gmail/api/quickstart/nodejs
I want to make part of the gmail API available to my MEAN app as a module. I've put the quickstart code into a model and I'm able to print the labels of my gmail account to the console.
Now I want to a) return arrays (of labels, messages, ...) instead of just printing them and b) reuse parts of the application for different use cases (e.g. authentication, ...)
The structure of the quickstart file is this:
- read client_secret asynchronously
- callback to authorization
- callback to getNewToken (if needed)
- callback to listLabels (Function that prints the labels)
In a synchronous world, what I would do is I'd create all these functions (getClientSecret, getAuthorization, getNewToken, listLables) and then call them one after another, like so:
function printLabels() {
secret = getClientSecret
auth = getAuthorization(secret)
token = getToken(auth)
labels = getLabels(auth)
print labels
}
To get all Threads, I'd do in a similar fashion:
function printThreads() {
secret = getClientSecret
auth = getAuthorization(secret)
token = getToken(auth)
threads = getThreads(auth)
print threads
}
Now I'm trying to do this in an asynchronous way and I just can't wrap my head around how to do this in a simple and elegant manner.
I want to re-use the code that's always the same and use the outcome (the auth object) for various queries (threads, labels, ...).
Can anyone point me to a good resource that will help me understand how to go about this?
Upvotes: 1
Views: 91
Reputation: 76905
When you work asynchronously, that is, you do not wait for a result, you need to use a promise, that is, something you expect from your code. A promise is pending first, then it is fulfilled or rejected. A promise expects a callback, that is, a function that will be executed when the async task is completed.
When you plan an async work-flow, you need to ask yourself the following questions:
These questions help you understand the life-cycle of async requests. The callback is the function executed at the finalization phase. Your callback can call any functions, you just need to do things expected after the task inside the callback, not after the function call.
Upvotes: 1
Reputation: 708
read about promises https://www.promisejs.org/ and generators https://davidwalsh.name/es6-generators
Upvotes: 0