在nodejs中同步修改对象

时间:2018-05-26 10:17:37

标签: node.js

当我修改对象属性时,我如何保证在nodejs中的另一行保证之前完成一行:

let getToken = function async (result) {

return new Promise(function (resolve, reject) {

    result = JSON.parse(result)[0];
     //how can i make sure that this line will execute before the next if(), despite nodejs is executing asynchronously   
     result.token = jwt.sign({
        data: 'foobar'
      }, 'secret', { expiresIn: '1h' });

    if(result.token){

        console.log('Res:'+ result.Age);
        resolve(result);
    }


});
}
就像你在注释行中看到的那样,当我修改对象属性时。如何确保下一行将在当前行操作后执行?

2 个答案:

答案 0 :(得分:1)

此函数不应该是异步的,因为jwt.sign可用作同步函数(读https://github.com/auth0/node-jsonwebtoken

const getToken = result => {
      const tmp    = JSON.parse(result)[0]
      result.token = jwt.sign({ data: 'foobar' }, 'secret', { expiresIn: '1h' });
      return result;
}

答案 1 :(得分:0)

使用await应该完成这项工作,只需将所有内容放入另一个异步函数中,使用await调用操作等待它完成。

以下代码未经过测试,例如

let getToken = function async (result) {

    return new Promise(async function (resolve, reject) { // change to async
        try{
            result = JSON.parse(result)[0];
            // The following line will wait for signJwt to return
            let token = await signJwt(jwt);
            if(token){
                console.log('Res:'+ result.Age);
                resolve(result);
            }
        }catch(e){
           // handle err...
        }
    });
}

async fucntion signJwt(jwt){
    // do what you need here

    return result;
}