How to make a Promise right?

  • 0
    There is a function foo (), in which there is an AJAX call to the server and a select-list is built. It is necessary to make the code in the then block work only after the select-list is rendered.

    let promise = new Promise(function (resolve, reject) {
        foo();
    });
    promise.then(result => {
        alert('done')
    });


    I wanted to put resolve () in foo ():

    function foo() {
        $.ajax({
            url: ......,
            type: 'get',
            dataType: 'json',
            data: data,
            success: function(data) {
                // ....
                resolve();
            },
            error: function(xhr, textStatus, errorThrown) {
                // ...
            }
        }
    }


    but an error occurs:

    Uncaught ReferenceError: resolve is not defined

    I understand that resolve cannot be nested? Can you fix this somehow?
    JavaScript Josephine Hood, May 16, 2020

  • 1 Answers
  • 0
    option 1.
    let promise = new Promise(foo);
    promise.then(result => {
    alert('done')
    });



    function foo(resolve, reject) {
    $.ajax({
    url: ......,
    type: 'get',
    dataType: 'json',
    data: data,
    success: function(data) {
    // ....
    resolve(data);
    },
    error: function(xhr, textStatus, errorThrown) {
    // ...
    reject(textStatus);
    }
    }
    }
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!