javascript - How do I transport this code from sync to async (nodejs)? -
i'm new node.js , concept of callbacks. have experience rails, php, etc. , i'm learning node.js.
i want create simple mail client uses google gmail api. sample code here: https://developers.google.com/gmail/api/quickstart/nodejs
i want make part of gmail api available mean app module. i've put quickstart code model , i'm able print labels of gmail account console.
now want a) return arrays (of labels, messages, ...) instead of printing them , b) reuse parts of application different use cases (e.g. authentication, ...)
the structure of quickstart file this:
- read client_secret asynchronously - callback authorization - callback getnewtoken (if needed) - callback listlabels (function prints labels)
in synchronous world, i'd create these functions (getclientsecret, getauthorization, getnewtoken, listlables) , call them 1 after another, so:
function printlabels() { secret = getclientsecret auth = getauthorization(secret) token = gettoken(auth) labels = getlabels(auth) print labels }
to threads, i'd in similar fashion:
function printthreads() { secret = getclientsecret auth = getauthorization(secret) token = gettoken(auth) threads = getthreads(auth) print threads }
now i'm trying in asynchronous way , can't wrap head around how in simple , elegant manner.
i want re-use code that's same , use outcome (the auth object) various queries (threads, labels, ...).
can point me resource me understand how go this?
when work asynchronously, is, not wait result, need use promise, is, expect code. promise pending first, fulfilled or rejected. promise expects callback, is, function executed when async task completed.
when plan async work-flow, need ask following questions:
- how should async task triggered? (event)
- what should happen after task triggered, before task started? (initialization)
- what should task? (purpose)
- what should passed? (specification)
- what should received? (response)
- what should happen after task has been completed? (finalization)
these questions understand life-cycle of async requests. callback function executed @ finalization phase. callback can call functions, need things expected after task inside callback, not after function call.
Comments
Post a Comment