Home > Enterprise >  How to wait for the end of the function
How to wait for the end of the function

Time:02-06

I have some task. I'm creating my library which has a connection function written in it (several processes are included) and a creation function. Need to clarify. The library doesn't deal with any http/https requests. Everything happens locally and without server requests.

Code from the testing side of the library

module.exports = async function connect(argument) {
    const { save, models } = argument;

    var prom = new Promise((resolve, reject) => {
        setTimeout(() => {
            checkDir(models);

            // check models
            checkBaseModels(models);
            checkModels(models);

            resolve();
        });
    });

    prom.then(() => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                loadModels();

                resolve();
            }, 2000);
        });
    }).then(() => {
        setTimeout(() => {
            saveModels(save);
            models_list();
        });
    });
};
const cloud = require('cloud');

const cloud = cloud.connect({ save: 1000 });

const create = cloud.create({
    name: "Test",
    description: "Abc"
});

What can be used to make other processes stop while the connection in my library is running.

I need to somehow fix this problem without using setTimeout and so on in the test. It is desirable to leave this code as it is.

I need to connect first, and then create. The code on the test side, if possible, should preferably not be edited.

CodePudding user response:

connect function is not returning the promise

module.exports.connect = async function connect(argument) {
  //  ...
  return prom;
}

Connection file

(async () => {
  const cloud = await cloud.connect({ save: 1000 });
  const create = cloud.create({
    name: "Test",
    description: "Abc",
  });
})();

CodePudding user response:

Код метода connect:

module.exports = async function connect(argument) {
    const { save, models } = argument;

    var prom = new Promise((resolve, reject) => {
        setTimeout(() => {
            checkDir(models);

            // check models
            checkBaseModels(models);
            checkModels(models);

            resolve();
        });
    });

    prom.then(() => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                loadModels();

                resolve();
            }, 2000);
        });
    }).then(() => {
        setTimeout(() => {
            saveModels(save);
            models_list();
        });
    });
};

In create, for now, the function is simply set to.

  • Related