use*_*103 7 javascript node.js async-await ecmascript-next
我目前正在编写用于个人用途的小型NodeJS CLI工具,我决定尝试使用Babel的ES7异步/等待功能.
它是一个网络工具,所以我显然有异步网络请求.我为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});
});
});
}
Run Code Online (Sandbox Code Playgroud)
现在我可以做点什么了
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();
Run Code Online (Sandbox Code Playgroud)
现在我有一个问题:我在许多地方提出要求,我必须将所有这些功能标记为async,这是一个好习惯吗?我的意思是我的代码中的几乎所有函数都应该是async因为我需要await来自其他async函数的结果.这就是为什么我认为我误解了async/await概念.
async/await有时被称为"传染性"或"病毒式"(或者它在C#世界中也是如此),因为为了使其有效,需要在调用链中一直支持它.强制异步执行同步操作可能会导致意外结果,因此您应该将其从原始方法一直延伸到使用它的顶级使用者.换句话说,如果您创建或使用使用它的类型,那么该类型也应该实现它,依此类推.所以是的,预计你会为每个依赖它的函数添加异步.但请注意,您不应该先抢先添加异步添加到实际上没有实现或需要它的函数.
试想一下:如果你使用async(通过await某种东西,我的意思),你就是async.避免将async呼叫压缩成同步的东西.
我在很多地方做过请求,我必须将所有这些功能标记为异步
是的,如果您的所有代码都是异步的,那么您将async在任何地方使用函数.
让所有代码都异步使事情变得复杂.你必须担心各地的竞争条件,确保正确处理可重入的功能,并记住在每一个await基本上任何事情都可能发生.
我的意思是我的代码中几乎每个函数都应该是异步的,因为我需要等待其他异步函数的结果.
这可能不是最佳做法.您可以尝试将代码分解为更小的单元,其中大多数通常不是异步的.所以不要写作
async function getXandThenDoY(xargs) {
let res = await get(xargs);
…
return …;
}
Run Code Online (Sandbox Code Playgroud)
你应该考虑做两个功能
function doY(res) {
// synchronous
…
return …;
}
function getXandDoY(xargs) {
// asynchronous
return get(xargs).then(doY);
}
/* or, if you prefer:
async function getXandDoY(xargs) {
return doY(await get(xargs));
}
*/
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1696 次 |
| 最近记录: |