JavaScript: how to deal with a function that requires a callback or promise?

0    29 Sep 2019 13:24 by u/user9713

I'm using an API that requires a callback or promise (up to the programmer), so I can't run this synchronously.

Here's the flow of my program:

  1. Receive input and validate it
  2. Instantiate a class using that input
  3. Use that class to call the API
  4. API requires callback or promise, as it takes about 3-5 seconds to query the data
  5. Program continues on since it's an async operation, but I need to display that query data
  6. Don't know how to wait for the data to finish, so program goes to outputting data that requires the class
  7. Program goes to shit since the class instance's field data is undefined

3 comments

0

Await the promise.. that is the point of them?

0

I was using this as a template and it didn't work. It just continued on.

var promise1 = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('foo');
  }, 300);
});
promise1.then(function(value) {
  console.log(value);
  // expected output: "foo"
});
console.log(promise1);
// expected output: [object Promise]
0

I don't see anything wrong there, besides the code being useless i mean..