0

I'm assigning values to an object and I need to assign a generated value that comes from an ajax response?

this is my assign code line:

    var object1 = object1.map(function(el) {
            var o = Object.assign({}, el);
            $.ajax({
                url: "/api/getcolor?age=7,  // this will return a sequence of object according to the item in object1 e.i {"color":"red"} {"color":"blue"} {"color":"yellow"}
                type: 'GET',
                dataType: 'json',
                success: function(data) {
                    console.log("data: "+JSON.stringify(Object.values(data)))
                   var myColors = JSON.stringify(Object.values(data))
                }
            });
            o.color= myColors ; // reassigning to object colors --> which means whatever was resturned from the ajax response should replaceeach value in object > o.color
}

my issue is, how do I access variable myColors outside of the ajax response and assign it to o.color? is there a better way of achieving this?

THANKS!

fosowe
  • 51
  • 8
  • 1
    `how do I access variable myColors outside of the ajax response` ... asynchronously - also, `myColors` will be a `String` - probably not what you want .... – Jaromanda X Sep 15 '20 at 07:52
  • 1
    Btw `Object.assign` is ES6 and `Object.values` is ES8 - not ES5 :-) – Bergi Sep 15 '20 at 07:52
  • if you `return $.ajax({` and move of the `o.color =` line inside the success function where it's available ... then you can `Promise.all(object1).then(function(results) { .... })` - in `....` you'll have all your results – Jaromanda X Sep 15 '20 at 07:54
  • @JaromandaX I was returning .. return o; let me try returning ajax as recommended – fosowe Sep 15 '20 at 07:56
  • 1
    TL;DR: this very much *is* a duplicate of those other questions. You're stumbling across the very basics of asynchronous processing the way every newbie stumbles across it eventually, and you need to accept it and deal with it, instead of trying to fight it. – deceze Sep 15 '20 at 08:10
  • @deceze I'm not denying anything... I'm thankful to have received help from Jaromanda - there are new thing i don't understand like ' Primise is not defined' when i clearly stated that i'm using ES5 or would want a solution compatible with ES5 – fosowe Sep 15 '20 at 08:12
  • jQuery `$.when()` is very similar to Promise.all . You can research how to pass array of ajax promises to it and how to handle the results using `apply()` in numerous questions on SO also – charlietfl Sep 15 '20 at 08:20

0 Answers0