Node.js/异步
来自康健生活
< Node.js
await
接收一个 promise 的时候,一种写法
initConfig.map(async (v, i) => {
const a = (await v).resources[0].el
await (await layers[i]).appendChild(a)
});
async
Promise
// bad
async function getUserInfo(id) {
const profile = await getUserProfile(id);
const repo = await getUserRepo(id)
return { profile, repo }
}
// good
async function getUserInfo(id) {
const [profile, repo] = await Promise.all([
getUserProfile(id),
getUserRepo(id)
])
return { profile, repo }
}
async function getServiceIP(name) {
// 从 DNS 和 ZooKeeper 获取服务 IP,哪个先成功返回用哪个
// 与 Promise.race 不同的是,这里只有当两个调用都 reject 时,才会抛出错误
return await Promise.any([
getIPFromDNS(name),
getIPFromZooKeeper(name)
])
}
No categories