Reputation: 956
how can i guarantee a line is done before another line in nodejs promise, when i am modifying an object property:
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);
}
});
}
like you see in comment line, when i am modifying object property. how can i make sure the next line will execute just after current line operation?
Upvotes: 0
Views: 50
Reputation: 26
Using await should do the job, just put everything inside another async function, use await to call the operation to wait for it to finish.
The following code is not tested, but for example
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;
}
Upvotes: 0
Reputation: 569
This function shouldn't be async, since jwt.sign is available as sync function (read 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;
}
Upvotes: 1