Node.js/异步:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
创建页面,内容为“== await == == async == == Promise == <syntaxhighlight lang="javascript"> // bad async function getUserInfo(id) { const profile = await getUserProfile(id); c…”
 
Kangkk​(留言 | 贡献)
 
第1行: 第1行:
== await ==
== await ==
接收一个 promise 的时候,一种写法
<syntaxhighlight lang="javascript">
initConfig.map(async (v, i) => {
  const a = (await v).resources[0].el
  await (await layers[i]).appendChild(a)
});
</syntaxhighlight>
== async ==
== async ==
== Promise ==
== Promise ==

2021年4月5日 (一) 12:51的最新版本

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)
    ])
}