Wait for the result of a function to save

2

How to execute a function and wait for a result to save the data:

I have

if (!_.isUndefined(image)){
    upload(image).then(function(response) {
      if (!response.success)
        return res.status(202).send(upload);

      image = response.image;  
    });
  }

dataProfile.save(function(err, data) {
  return res
      .send({
        success: true,
        data: data
      });
});

but when I run, when I save the value of image it takes it undefined or it takes a previous value because it has not finished executing the function. How would you expect the result of the function and save it?

    
asked by Pxion 12.09.2016 в 15:41
source

1 answer

1

You can use the Co library for better pledge management if you want to use a synchronous style code.

co(*() => {
  let response = yield upload(image);
  // hacer algo con la respuesta
}).catch((err) => {

});

Or if you want to use the next ES8 and its Async / Await news, you can use Babel to transpile it to ES5. This is my preferred method.

let response = await upload(image);
// hacer algo con la respuesta

If you prefer the promises, as you have it, you must first convert the answer to JSON, like this:

upload(image)
  .then(res => res.json())
  .then(data => {
    // aqui data ya es un objeto
  });

Keep in mind that JavaScript is an asynchronous language, so that within a callback you can not return out of the main function.

    
answered by 12.09.2016 в 16:06