E
E
Eugene2019-10-20 22:10:49
css
Eugene, 2019-10-20 22:10:49

How to improve query packaging?

I'm trying to implement a feature to package requests. The essence of its work is to collect requests in a pack of 25 pieces and send them with an interval of 50ms. Upon execution, the response should return to the function that sent the request.
I'm new to javascript, it would be helpful to hear criticism from advanced developers.

// Пример вызова функции
await vk("get.user", { user_id: 1 });

When a function is called, it is wrapped in a promise and an object with parameters, resolve and reject is placed in an array.
let queue = [];

function vk(method, data = {}) {
        return new Promise((resolve, reject) => {
            const query = `API.${method}(${JSON.stringify(data)})`;
            queue.push({ resolve, reject, query });
        });
};

The second function extracts the first 25 calls from the array every 50ms, packs and makes a request. After that, the response is iterated over in the array and the caller's resolve() is called with the result of the request.
setTimeout(async function execute() {
    const queuePart = queue.splice(0, 25);

    if (queuePart.length !== 0) {
        const code = `return [${queuePart.reduce((chunk, { query }) => `${chunk}${query},`, "")}];`;
        const response = await request(code);

        for (let i = 0, len = response.length; i < len; i++) {
            const { resolve } = queuePart[i];
            resolve(response[i][0]);
        };
    };
    setTimeout(execute, 50);
}, 50);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
noys, 2018-08-09
@noys

Just look at the source code

S
Stockholm Syndrome, 2019-10-20
@you_are_enot

resolve(response[i][0]);

why [0]? request packaging can be used for any methods where the response structure may not be an array
, you can add error handling
if the response is false, then the method returned an error, which is placed in the array of execute_errors objects, that is, you can write something like this:
const { response, execute_errors } = await request(code);

for (let i = 0, len = response.length; i < len; i++) {
  const { resolve, reject } = queuePart[i];
  if (response[i] === false) {
    reject(execute_errors.shift());
  } else {
    resolve(response[i]);
  }
};

but at the same time, request must return the full response from the execute method, and not just the response field

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question