Javascript - Dynamic Function Call -
how below return value?
var data = sql.execute({query:"select * profile_user"}).then(function (result){ return result; // actual result = [{id:1, name:"mr. test"}] }, function( err ) { console.log( "something bad happened:", err ); }); console.log("received data"+json.stringify(data));
result in console : received data{"_handler":{"resolved":false}}
as answered above - function returns promise, result defined when promise resolved (or not defened if promise failed).
the best practice here build async program way, when code, requires result placed on result/reject promise callbacks:
var data = sql.execute({query:"select * profile_user"}).then(function (result){ console.log("received data"+json.stringify(data)); // doing data }, function( err ) { console.log( "something bad happened:", err ); });
if need "wait" while promise resolved - can use new async/await feature, may understand, thit stuff stop thread execution until promise resolution.
in case need wrap async code async function, this:
async executesqlanddosomething () => { try { var data = await sql.execute({query:"select * profile_user"}) // thread stop here console.log(data) // doint data } catch (err) { // ... error checks } }
read more info async/await here: https://developer.mozilla.org/en-us/docs/web/javascript/reference/operators/await
Comments
Post a Comment