Jump to content

Javascript Interview Question help!


andy246
 Share

Recommended Posts

This is a question I got asked in an interview. I know the array would just return zeros since this is asynchronous, but why does this happen, and how can you fix it so that the results array inserts the appropriate data?

Question: Suppose findData is a function that takes a query object and returns a promise for the result of the query. Suppose also that someRandomArrayOfQueries is an array of query objects. Explain what would be printed by the following code and why:

function runMultipleQueries(queries) { var results = []; queries.forEach(doQuery); return results; function doQuery(query) { findData(query) .then(results.push.bind(results)); } }function log(value) { console.log(value);}runMultipleQueries(someRandomArrayOfQueries).forEach(log);

Link to comment
Share on other sites

  • 2 weeks later...

The only thing that throws me off is this:

results.push.bind(results)

The push method is used to add an element to an array. As far as I know, it doesn't have a bind() method.

Link to comment
Share on other sites

OK. What seems to be missing is arguments for the push method.

 

Oh, actually. The promise passes the parameter.

 

I guess the solution for the asynchronous problem would be to have a callback when all the queries were done.

Edited by Ingolme
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...