Search code examples
javascriptnode.jsloopback

Wait for Callbacks to complete before returning to the user


I have a dynamic case where user will post a array of data which i need to insert into the database in different rows. How do i wait for the calls back to complete before returning success or failure to the user.

I tried using promise but it returns this

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined (node:6216) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

My trails with promises

req.targetting.forEach(data => {
      let s = {};
      if (data.value == '' || data.value.length == 0) {
        s = 99;
      } else {
        s = data.status;
      }
      let promises =  new Promise((resolve, reject) => {
        XXX.upsertWithWhere(where clause,data, (err, data) => { // a loopback method
            if (err) {
              return reject(err);
            }
            return resolve(data);
          });
      });
      Promise.all(promises).then((err, data) => {
        if (err) {
          return callback(err);
        }
        callback(null, data);
      });
    });
  };

I thought of put promises out side but still the same error with rejection id 3

The signature for the upsert method

PersistedModel.upsertWithWhere([where], data, callback)

Solution

  • I guess something like this should be fine(I didnt test this code)

    let promises = [];
    req.targetting.forEach(data => {
    let s = {};
    if (data.value == '' || data.value.length == 0) {
      s = 99;
    } else {
      s = data.status;
    }
    let promise =  new Promise((resolve, reject) => {
      XXX.upsertWithWhere(whereclause,data, (err, data) => { // a loopback 
      //method
      if (err) {
        return reject(err);
      }
        return resolve(data);
      });
    });
    promises.push(promise);
    });
    Promise.all(promises).then((data) => {
      return data;
    })
    .catch((err) => {
      return err;
    });