I'm currently writing small NodeJS CLI tool for personal usage and I've decided to try ES7 async/await feature with Babel.
It's a network tool so I obviously have asynchronous network requests. I wrote a simple wrapper for request
package:
export default function(options) {
return new Promise(function(resolve, reject) {
request({...options,
followAllRedirects: true,
headers: {
"user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0"
}
}, (error, response, body) => {
if(error) {
return reject(error);
}
resolve({response: response, body: body});
});
});
}
Now I can do something like
async function getGooglePage() {
try {
var r = await request({url: "http://google.com"});
console.log(r.body);
console.log("This will be printed in the end.")
} catch(e) {
console.log(e);
}
}
getGooglePage();
And now I have a question: I do requests in many places and I have to mark all these functions as async
, is it a good practice? I mean that almost every function in my code should be async
because I need to await
a result from other async
functions. That's why I think that I misunderstood async/await concept.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…