Node.js/异步

来自康健生活
Kangkk​(留言 | 贡献)2020年2月23日 (日) 07:27的版本 (创建页面,内容为“== await == == async == == Promise == <syntaxhighlight lang="javascript"> // bad async function getUserInfo(id) { const profile = await getUserProfile(id); c…”)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)

await

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