node异步的问题

彼岸花开
  • 491

clipboard.png

router.get('/decoded', async(ctx, next) => {
    var ctx_query = ctx.query
    var decoded;

    jwt.verify(ctx_query.token, secret,
        // await
        async function(err, decoded) {
            if (err) { console.log(err) } else {
                console.log(decoded)  //这里有值
                return await decoded
            }
        })

    ctx.body = {
        'decoded': await decoded   //这里没值 
    }


})
回复
阅读 938
5 个回答
✓ 已被采纳

试试:

const data = await new Promise((resolve, reject) => {
     jwt.verify(ctx_query.token, secret, function(err, decoded) {
            if (err) { console.log(err) } else {
                resolve(decoded);
            }
        });
});

ctx.body = {
    decoded: data
}
router.get('/decoded', async(ctx, next) => {
    var ctx_query = ctx.query
    var decoded = await jwt.verify(ctx_query.token, secret);
    ctx.body = {
        'decoded': decoded
    }
})

(Synchronous) If a callback is not supplied, function acts synchronously. Returns the payload decoded if the signature (and, optionally, expiration, audience, issuer) are valid. If not, it will throw the error.

https://www.npmjs.com/package...

var EventEmitter = require('events').EventEmitter; 
var event = new EventEmitter();

var decoded;
event.on('resolved', function(data) { //监听事件
    decoded = data;
}); 
jwt.verify(ctx_query.token, secret,
    
    function(err, decoded) {
        if (err) { console.log(err) } else {
            console.log(decoded)  //这里有值
            event.emit('resolved',decoded);//数据来了触发事件并传递数据
        }
    })

试试用promise 去修改你的请求

var promise = new Promise(function(resolve, reject) {
 if (/* 异步操作成功 */){
 resolve(value);
 } else {
 reject(error);
 }
});

promise.then(function(value) {
 // success
}, function(value) {
 // failure
});
你知道吗?

宣传栏