最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Async context tracking, async_hooks - Stack Overflow

programmeradmin3浏览0评论

I'm trying to better understand the output from node async_hooks. It's not giving me the output I expect. Specifically, I'd expect that each new async function creates a new asynchronous context. So that all asynchronous processes spawned therein would have THAT (the function which starts the new process) as it's asyncTriggerId.

Can someone help clarify how to make this happen? Or where my expectations are misguided?

I have a basic example here:

import async_hooks from 'async_hooks';

const hook = async_hooks.createHook({
    init(asyncId, type, triggerAsyncId) {
        console.log(`[INIT] asyncId: ${asyncId}, type: ${type}, triggered by: ${triggerAsyncId}`);
    },
});

hook.enable();


async function A(){
    console.log("A");
    return await B();
}

async function B(){
    console.log("B")
    C();
    return "b";
}

async function C(){
    console.log("C")
    return "c";
}



function CALLBACK(){
    console.log("DONE");
    console.log(process.allPromises)
}

A().then(CALLBACK);

And the output is:

[INIT] asyncId: 6, type: PROMISE, triggered by: 1
[INIT] asyncId: 7, type: TickObject, triggered by: 1
A
[INIT] asyncId: 8, type: PROMISE, triggered by: 1
B
[INIT] asyncId: 9, type: PROMISE, triggered by: 1
C
[INIT] asyncId: 10, type: PROMISE, triggered by: 8
[INIT] asyncId: 11, type: PROMISE, triggered by: 6
DONE
[INIT] asyncId: 12, type: TickObject, triggered by: 11
undefined
[INIT] asyncId: 13, type: TickObject, triggered by: 11
[INIT] asyncId: 14, type: TickObject, triggered by: 11
发布评论

评论列表(0)

  1. 暂无评论