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

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -