Skip to content

How to make this cls work with async function #98

Open
@foreverpw

Description

@foreverpw

I have below test code, executed in nodejs 7.4.0 with --harmony-async-await argument.

function newP(id){
    Promise.resolve().then((data)=>{
        ns.run(function(){
            ns.set('cid',id)
            afn()
        })
    })
}
async function afn(){
    var a1 = await log(1)
    var a1 = await log(2)
}
function log(index){
    return new Promise(function (resolve, reject){
         console.log('cid:'+ns.get('cid')+',index:'+index)
         resolve()
    })
}
newP(1);
newP(2);

and the output is:

cid:1,index:1
cid:2,index:1
cid:undefined,index:2
cid:undefined,index:2

what I think it should be is:

cid:1,index:1
cid:2,index:1
cid:1,index:2
cid:2,index:2

It seems that the context is lost, but when I changed the async function to Generator and ran with co, it works well.

function* gen(){
    var a1 = yield log(1)
    var a2 = yield log(2)
}

function newP(id){
    Promise.resolve().then((data)=>{
        ns.run(function(){
            ns.set('cid',id)
            co(gen);
        })
    })
}

newP(1);
newP(2);

So how can I get it work with async function.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions