R
R
Roman2020-09-25 11:47:03
JavaScript
Roman, 2020-09-25 11:47:03

How to get return value from ajax request?

Good afternoon!

I registered my js-library for working with goods in the Bitrix24 box.

I ran into a problem:

I make a request to the module through BX.ajax.runAction, for convenience I wrapped the call in a separate asynchronous function:

ProductData.post = async function (actionName, params = {}) {

    let action = 'ramapriya:productdata.api.calculator.' + actionName;

    const request = await BX.ajax.runAction(action, {
        method: 'POST',
        data: params
    });

    return await request.data;
}


So, when I call this function inside another one, I can’t figure out how to pull data out of it for use in other places in the library:

const inputNames = this.post('getProductPropertiesNames', {
    productId: this.extractProductId(window.location.href)
});

let inputs;

inputNames.then(response => {
    console.log(response.inputs) // работает, возвращает нужный результат
    inputs = response.inputs;
})

console.log(inputs) // undefined


Tell me what and where I'm doing wrong.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tim, 2020-09-25
@Tim-A-2020

The word async has one simple meaning: this function always returns a promise. Values ​​of other types are wrapped in a successfully completed promise automatically - Source . To get data, you need to use an asynchronous function or through then.
Example 1

...
ProductData.post().then(data => console.log(data));

Example 2
(async function() {
    const response = await ProductData.post();
    console.log(response);
})()

You can use callback
inputNames.then(response => {
    console.log(response.inputs) // работает, возвращает нужный результат
    test(response.inputs);
})

function test(inputs) {
  console.log(inputs)
}

inputs = undefined - because at the time of execution, the promise has not yet completed.
If you fundamentally want to use a synchronous request, then use synchronous ajax. On Bitrix I don't know how to do it. The browser will be blocked for the duration of the request.
let response = $.ajax({async: false, ...}).responceText;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question