我目前正在编写一个用于个人使用的小型NodeJS CLI工具,并决定尝试使用Babel的ES7 async/await功能。
由于这是一个网络工具,所以我显然有异步网络请求。我为request
包编写了一个简单的包装器:
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});
});
});
}
现在我可以做一些像这样的事情
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();
现在我有一个问题:我在许多地方进行请求,我必须将所有这些函数标记为async
,这是一个好的实践吗?我的意思是我的代码中几乎每个函数都应该是async
,因为我需要从其他async
函数中等待结果。这就是我认为我误解了异步/等待的概念的原因。
async
/await
只是语法糖。再次强调,我认为混合这两个概念是创造预期结果的好方法,但我理解你的意思,即在C#世界中,编译器要求使用它,这加强了它的传播性,但在JavaScript中没有这样的事情。 - moribvndvs