1

I have a function that return something like [object object] no my value that I wanted , I do almost every thing to get the value but no hope.

When I try to show that object using toSource() I got something like that.

({state:(function (){return state;}), always:(function (){deferred.done(arguments).fail(arguments);return this;}), then:(function (){var fns=arguments;return jQuery.Deferred(function(newDefer){jQuery.each(tuples,function(i,tuple){var action=tuple[0],fn=fns[i];deferred[tuple[1]](jQuery.isFunction(fn)?function(){var returned=fn.apply(this,arguments);if(returned&&jQuery.isFunction(returned.promise)){returned.promise().done(newDefer.resolve).fail(newDefer.reject).progress(newDefer.notify);}else{newDefer[action+"With"](this===deferred?newDefer:this,[returned]);}}:newDefer[action]);});fns=null;}).promise();}), promise:(function (obj){return obj!=null?jQuery.extend(obj,promise):promise;}), pipe:(function (){var fns=arguments;return jQuery.Deferred(function(newDefer){jQuery.each(tuples,function(i,tuple){var action=tuple[0],fn=fns[i];deferred[tuple[1]](jQuery.isFunction(fn)?function(){var returned=fn.apply(this,arguments);if(returned&&jQuery.isFunction(returned.promise)){returned.promise().done(newDefer.resolve).fail(newDefer.reject).progress(newDefer.notify);}else{newDefer[action+"With"](this===deferred?newDefer:this,[returned]);}}:newDefer[action]);});fns=null;}).promise();}), done:(function (){if(list){var start=list.length;(function add(args){jQuery.each(args,function(_,arg){var type=jQuery.type(arg);if(type==="function"){if(!options.unique||!self.has(arg)){list.push(arg);}}else if(arg&&arg.length&&type!=="string"){add(arg);}});})(arguments);if(firing){firingLength=list.length;}else if(memory){firingStart=start;fire(memory);}}
return this;}), fail:(function (){if(list){var start=list.length;(function add(args){jQuery.each(args,function(_,arg){var type=jQuery.type(arg);if(type==="function"){if(!options.unique||!self.has(arg)){list.push(arg);}}else if(arg&&arg.length&&type!=="string"){add(arg);}});})(arguments);if(firing){firingLength=list.length;}else if(memory){firingStart=start;fire(memory);}}
return this;}), progress:(function (){if(list){var start=list.length;(function add(args){jQuery.each(args,function(_,arg){var type=jQuery.type(arg);if(type==="function"){if(!options.unique||!self.has(arg)){list.push(arg);}}else if(arg&&arg.length&&type!=="string"){add(arg);}});})(arguments);if(firing){firingLength=list.length;}else if(memory){firingStart=start;fire(memory);}}
return this;})})

Could any one explain me? And I know my function is Asynchronous.

How could solve this problem ?

Here is my code:

  module.Order = Backbone.Model.extend({
        initialize: function (attributes) {
            Backbone.Model.prototype.initialize.apply(this, arguments);
            this.pos = attributes.pos;
            this.sequence_number = this.pos.pos_session.sequence_number++;
            debugger;
            var odoo = []
            var call = this
            this.uid = this.generateUniqueId();
            this.pro = this.get_the_other_main().done(
                function (result) {
                }).always(function (result) {
                    odoo.push(result)
                    call.set({
                creationDate: new Date(),
                orderLines: new module.OrderlineCollection(),
                paymentLines: new module.PaymentlineCollection(),
                name: _t("Order ") + this.uid,
                client: null,
                sales_person: null,
                sales_person_name: null,
                new_id: odoo[0]
            })});
            alert(odoo[0])//// Must be adddddedd
            this.selected_orderline = undefined;
            this.selected_paymentline = undefined;
            this.screen_data = {};  // see ScreenSelector
            this.receipt_type = 'receipt';  // 'receipt' || 'invoice'
            this.temporary = attributes.temporary || false;
            return this;
        },
get_the_other_main: function () {
            var dfd = new jQuery.Deferred();
            new instance.web.Model("pos.order").call('get_the_product', []).done(
                function (results) {
                    var result = results.toString().split(',');
                    var stringsl = result[1];
                    var thenum = stringsl.replace(/^\D+/g, '');
                    var sasa = parseInt(thenum, 10) + 1
                    var zika = ('00' + sasa).slice(-4)
                    var the_str = result[1].slice(0, -4).toString();
                    var new_seq_sasa = the_str + zika
                    dfd.resolve(new_seq_sasa);
                }).always(function(results) {
                    var result = results.toString().split(',');
                    var stringsl = result[1];
                    var thenum = stringsl.replace(/^\D+/g, '');
                    var sasa = parseInt(thenum, 10) + 1
                    var zika = ('00' + sasa).slice(-4)
                    var the_str = result[1].slice(0, -4).toString();
                    var new_seq_sasa = the_str + zika
                    dfd.resolve(new_seq_sasa);
                }).always(function(results) {
                    var result = results.toString().split(',');
                    var stringsl = result[1];
                    var thenum = stringsl.replace(/^\D+/g, '');
                    var sasa = parseInt(thenum, 10) + 1
                    var zika = ('00' + sasa).slice(-4)
                    var the_str = result[1].slice(0, -4).toString();
                    var new_seq_sasa = the_str + zika
                    dfd.resolve(new_seq_sasa);
                });
            alert('')////If i remove that it will return undefind for this.pos
            return dfd
Mostafa Mohamed
  • 816
  • 15
  • 39
  • It could be your code isn't waiting for the asynchronous call to return before executing. So you're not getting an object of the type you're expecting. Check to make sure your callbacks are set up correctly. – The Disco Spider Nov 04 '15 at 17:19
  • already checked ,,, please read my comments in the code .. how could i arrange that calls ? – Mostafa Mohamed Nov 04 '15 at 17:23
  • Even with your edit, your `this.set` occurs before `this.get_the_other_main().done` so it is wrong ! – Anonymous0day Nov 04 '15 at 18:12
  • You ***must*** [read this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) to be able to resolve your issue – Anonymous0day Nov 04 '15 at 20:31

1 Answers1

3

You seem to have problem of asynchronous call.
(see the comments below)

// you call get_the_other_main which return a Promise ! 
        this.get_the_other_main().then(
            function (result) {
// when the Promise resolve you set this.pro, 
// what is this here ?? are you sure of the beahviour ?
//               |
//               V
                this.pro=result//got it right <---------------------- +
//                                                                    |
//                                                                    |
        });//                                                         |
// You set this.pro to another Promise, at this moment the previous this.pro is not set !
        this.pro=this.get_the_other_main().then(
            function (result) {
                 this.pro=result //got it right <----------------------------------------+
        }); //                                                                           |
// when you call alert, this.pro is a Promise not resolved !at this moment the previous this.pro is not set !

        alert(this.pro.toSource()) //[object object] 
// logicaly it show the code source of your deffered / Promise !

to solve your issue try like that :

module.Order = Backbone.Model.extend({
  initialize: function(attributes) {

    var curOrder = this;

    Backbone.Model.prototype.initialize.apply(this, arguments);

    this.pos = attributes.pos;
    this.sequence_number = this.pos.pos_session.sequence_number++;

    debugger; // ??????

    this.uid = this.generateUniqueId();
    var odoo = []

    this.get_the_other_main().then(
      function(result) {
        curOrder.pro = result; //got it right

        curOrder.set({
          creationDate     : new Date(),
          orderLines       : new module.OrderlineCollection(),
          paymentLines     : new module.PaymentlineCollection(),
          name             : _t("Order ") + curOrder.uid,
          client           : null,
          sales_person     : null,
          sales_person_name: null,
          new_id           : curOrder.pro 
        });

        curOrder.selected_orderline   = undefined;
        curOrder.selected_paymentline = undefined;
        curOrder.screen_data          = {}; // see ScreenSelector
        curOrder.receipt_type         = 'receipt'; // 'receipt' || 'invoice'
        curOrder.temporary            = attributes.temporary || false;

       curOrder.trigger('orderready' , curOrder);

      });

    return this; 
// be careful because the process above is not done again, when you return this, it will be resolved later
  },
  get_the_other_main: function() {
    var dfd = new jQuery.Deferred();
    new instance.web.Model("pos.order").call('get_the_product', []).done(
      function(results) {
        var result = results.toString().split(',');
        var stringsl = result[1];
        var thenum = stringsl.replace(/^\D+/g, '');
        var sasa = parseInt(thenum, 10) + 1
        var zika = ('00' + sasa).slice(-4)
        var the_str = result[1].slice(0, -4).toString();
        var new_seq_sasa = the_str + zika
        dfd.resolve(new_seq_sasa);
      });
    return dfd
  },
Anonymous0day
  • 3,012
  • 1
  • 14
  • 16
  • I sole my problem by a trick that i do but i face one problem here ,, i updated the code look at my get_the_other_main function ,, when i add that alert it prints the value correctly ,, when i remove that alert .. it return undefind ,, so how could i complete my trick ? – Mostafa Mohamed Nov 04 '15 at 17:59
  • Code updted ,, code you explain why is that happen ? and how could i trick this alert ? – Mostafa Mohamed Nov 04 '15 at 18:01
  • @MostafaMohamed i have updated my answer reflecting your need ! – Anonymous0day Nov 04 '15 at 18:08
  • your code did not work ,, that i could run the set function inside the result function! – Mostafa Mohamed Nov 04 '15 at 18:40
  • Please look in my code it works but i must use that last empty alert to print the value correctly : – Mostafa Mohamed Nov 04 '15 at 18:45
  • @MostafaMohamed i 've looked your code but ***it can't work*** like you do ! what didn't work in my code ? have you got an error ? what kind of error ? – Anonymous0day Nov 04 '15 at 19:06
  • It's Pos application Of odoo/openERP if you familiar with ,, when i run your code it shows me blank black page,, but my code return the value correctly just if i put the (alert('')////If i remove that it will return undefind for odoo[0]) unless it will print undefined to me ?!! – Mostafa Mohamed Nov 04 '15 at 19:11
  • this behavior is strange it must be the sequence of the function codes but why when i add that alert it works perfectly! – Mostafa Mohamed Nov 04 '15 at 19:16
  • No your code don't return the value correctly ! i'am not familiar with odoo, but it is not specific to odoo, it is a problem of Promise chain ! when you call `alert(odoo[0])` odoo is equal to `[] ` because `odoo.push(result)` have not been called yet ! – Anonymous0day Nov 04 '15 at 19:17
  • I updated my code to my last case which match what you said but i still have to add this alert !! – Mostafa Mohamed Nov 04 '15 at 19:22
  • Code updated now alert(odoo[0])//// Must be adddddedd it shows undefined but the final value i got in the view is right. – Mostafa Mohamed Nov 04 '15 at 19:23
  • @MostafaMohamed it is deferred, when you call `alert('')` you stop the current process until you click, during this time the previous asynchronous call finish, so your deferred is fulfiled at the moment you click on alert – Anonymous0day Nov 04 '15 at 19:54
  • Hmmm i start to understand this.. So i don't want to show this alert again.. But i need to do the same functionality.. How could i do this? Thanks – Mostafa Mohamed Nov 04 '15 at 19:59
  • you just have to copy my code, it should work, but i need to know what happen befor and after `initialize`, what code call this part to be more precise ! – Anonymous0day Nov 04 '15 at 20:11
  • I copy and paste your code ,,, it just show blank black page ,,, and if i add alert before the return of initialize function ,, it returns the correct value :/ same problem again! – Mostafa Mohamed Nov 04 '15 at 20:32
  • I have understood that, but this is about what happen to `module.Order` once it is initialized because in reality your code is asynchronous, but if you have something like `var myOrder = new module.Order(); myOrder.doSomething()` the doSomething go wrong because the initialize haven't finished yet in reality ! if you want you can use an event once you set the new_id you trigger it and listen to this event after creating your Order – Anonymous0day Nov 04 '15 at 20:54
  • event like what ? i need useless one just to take the time.what should i do then ? – Mostafa Mohamed Nov 04 '15 at 20:56
  • i updated my code whit `curOrder.trigger('orderready' , curOrder);` so in the part of your code (not shown) calling `var myO = new module.Order();` just listen to `myO.on('orderready' , function(model){ do here what you want })` – Anonymous0day Nov 04 '15 at 21:38
  • Soryy i couldn't understand what you explain now ? what do you mean by not shown? – Mostafa Mohamed Nov 04 '15 at 21:57
  • your code start by `module.Order = Backbone.Model.extend({` this is for module.Order creation, right ? so the code calling this part is not show in the part of code you provide ! – Anonymous0day Nov 04 '15 at 22:06
  • it's Called here : module.OrderCollection = Backbone.Collection.extend({ model: module.Order, }); What should i add to this ? – Mostafa Mohamed Nov 04 '15 at 22:12
  • ***No*** this is the definition part, i need to see the ***instantation*** , the creation part of your object usin this part of code ! – Anonymous0day Nov 04 '15 at 22:29
  • I can't edit the original code! i must inherit it and work to edit it not change in the original! – Mostafa Mohamed Nov 04 '15 at 22:34
  • @MostafaMohamed check [this fiddle](http://jsfiddle.net/swk065L9/5/) and come back to tell me about it ! read ***carefully*** the end `instanciation & execution`! – Anonymous0day Nov 05 '15 at 00:06
  • I read it quickly .. but i don't know where to put my code?! sorry :( – Mostafa Mohamed Nov 05 '15 at 00:18
  • i could show you my whole code if you want to edit on it :) Thanks – Mostafa Mohamed Nov 05 '15 at 00:19
  • Thanks .. here is my whole code! i couldn't know how to update it. http://jsfiddle.net/ronozoro/gf3qsm24/ – Mostafa Mohamed Nov 05 '15 at 00:31
  • that strange thing that when ever i add alert in the function before return dft or in the initializefunction before return this,, it works correctly! is there is no way to execute the alert box and hide it again or just trigger in silence ! – Mostafa Mohamed Nov 05 '15 at 01:09
  • Have you ***just tried to understand*** the fiddle i provide to you ? for more explanation you [should read this](https://doc.odoo.com/trunk/web/rpc/) i am not sure you can do what you want with your pattern ! [And read also about Promises](http://www.html5rocks.com/en/tutorials/es6/promises/) – Anonymous0day Nov 05 '15 at 08:18
  • Ok will do that .. but what do you suggest in my code please ? – Mostafa Mohamed Nov 05 '15 at 08:25
  • I already did! but i'm not JavaScript or Jquery geek ,, i just wanna to see the solution and understand it ,, i almost try every thins ,, referring to your odoo rpc call link i already read but query doesn't fit me. – Mostafa Mohamed Nov 05 '15 at 08:40
  • Re-think your pattern, read the doc about odoo, use the method provided by odoo ! – Anonymous0day Nov 05 '15 at 08:41
  • ***i just wanna to see the solution and understand it*** it is not possible we can not guess what you want ! i don't know why you use `get_the_other_main` in the definition of an **instanciation** – Anonymous0day Nov 05 '15 at 08:42
  • You don't know what is a Promise / Deferred but you use it and ask people to help debugging, it is quasi impossible to help you if you don't understand, if you are not a Javascript geek it is time to become one – Anonymous0day Nov 05 '15 at 08:45
  • **I have read** odoo source code and there is a big difference between yours and original, so from where come your code ? what are trying to achieve ? – Anonymous0day Nov 05 '15 at 08:49
  • Just wanna get the last order code and add it to 1 then print in the receipt. so i call a function python get_the_product that execute a sql statement then return the result and i do some work with this result ,, then i pass it to initialize function to initialize the id this receipt everytime i create one.What i achieve for now works very correct just i have some problems with the Deferred .. if i return dft.resolve() the value wil be undefind if i return just dft it will not load to pos and i have to add alert to get the desired output.this is my whole case and what i want to achive – Mostafa Mohamed Nov 05 '15 at 09:02
  • `last order code and add it to 1` this is a bad design, it is not at client side to determine this, but at saving time ! what happend if 3 users try to add an order at the same time ? user 1 get last number 3333, your code add 1 and become 3334, it take severals minutes to fill the order, in the same time user 2 get last number 3333 TOO and become 3334 user 2 save it before user 1, what become user1's order ? – Anonymous0day Nov 05 '15 at 10:35
  • Only one user here and i know that. this design fit my needs.I thinked aout something but you could help me more,, what if i fire alert and then quickly press enter button automatically?! i think it will do the trick .but i don't know how to fire enter button automatically after alert.. could you help me please ? I'm Python developer not jquery or jaرascript developer but i still try :/ – Mostafa Mohamed Nov 05 '15 at 10:50
  • If **really** you want help go and read **ALL** of [that page](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call?rq=1) and come back and we going to start – Anonymous0day Nov 05 '15 at 10:53
  • but it's ajax example do you think it will fit my case ? – Mostafa Mohamed Nov 05 '15 at 10:57
  • This is a matter with you, you don't want to read, i can help you, but you don't want ! why ? have you read ALL of that page ???? how can i advice you if i am sure you will not understand ? **YOUR ISSUE IS A MATTER OF ASYNCHRONOUS** like ajax !!!! if you understand that you will understand your issue and find THE way of resolution !!! – Anonymous0day Nov 05 '15 at 11:00
  • I already read it and tried all soulation he offers in that thread i really do and try almost every thing ,, before i start i didn't know anything now i could write that could we argue about but i can't understand the behavior ! – Mostafa Mohamed Nov 05 '15 at 11:04
  • This is exactly the same as [Python Futures](https://docs.python.org/dev/library/concurrent.futures.html) maybe it will help you ! – Anonymous0day Nov 05 '15 at 11:07
  • from what i read and understand ,, that it should run perfect when i return dft.resolve() from my get_the_other_main function ,, but i keep tell my that the value of result in initializeis undefined ! – Mostafa Mohamed Nov 05 '15 at 11:07
  • Just read ! but you don"t want ! you prefer waste you time ! so once again : you NEVER return dfd.resolve() ! you call it !!! before that you return `dfd` object, this object is **ASYNCHRONOUS** when you return it, the value is not defined, it will be defined **LATER** when you `call a function python get_the_product that execute a sql statement then return the result and i do some work with this result ,, then i pass it to` <--- THIS TAKE TIME after that time you call `dfd.resolve(result)` in another word you send the value result to the function that is "WAITING" – Anonymous0day Nov 05 '15 at 11:13
  • Imagine you make a phone call to a friend and ask him to look something up for you. Although it might take a while, you wait on the phone and stare into space, until your friend gives you the answer you needed, this is SYNCHRONOUS ! – Anonymous0day Nov 05 '15 at 11:18
  • ASYNCHRONOUS : You call your friend again for the same reason. But this time you tell him that you are in a hurry and he should call you back on your mobile phone. You hang up, leave the house and do whatever you planned to do. Once your friend calls you back, you are dealing with the information he gave to you. – Anonymous0day Nov 05 '15 at 11:19
  • hmmmmmmm i GOT it then you mean that function (results) {} in get_the_other_main function doesn't run for the first time ,,, the return run before it right?! then the function results called after initialize then the value is not defiend but when i go for the alert the alert time make the call of the function(result) and return the right value . but hat after the initialize. Right?! – Mostafa Mohamed Nov 05 '15 at 11:21
  • That's exactly what's happening when you do `this.get_the_other_main().then()` : this.get_the_other_main() is your phone call and it is now BUT the then part is executed LATER ! – Anonymous0day Nov 05 '15 at 11:21
  • Thanks my friend ..But i still don't konw how to arrrange that calls :/ i understand the behavior but i couldn't stop function process without alert. what could i do else?! – Mostafa Mohamed Nov 05 '15 at 11:24
  • And this is all the problem ! once you are in a Promise chain you can't get out of it ! it is why i suggest you to trigger an event at creation / instantacion time – Anonymous0day Nov 05 '15 at 11:27
  • Do you mean event like firing alert? – Mostafa Mohamed Nov 05 '15 at 11:34
  • i know that i want to trigger event like alert to get more time to finish the process but alert is a stupid thing ,, what could else i do to take that time ? i could edit in the original code and i will figure it later so how could i create event in the creation / – Mostafa Mohamed Nov 05 '15 at 11:38
  • no, alert is not an event ! see my code there is `curOrder.trigger('orderready' , curOrder);` but you have to be familiar with javascript's event and backbone – Anonymous0day Nov 05 '15 at 11:40
  • useless or silence event without showing anything in the screen. – Mostafa Mohamed Nov 05 '15 at 11:40
  • it is exactly what i provide you from the begining ! – Anonymous0day Nov 05 '15 at 11:42
  • i know but i could not understand it or where should i add this event or where to call it ?! i showed you my whole code but you didn't tell me where should i create it ?! – Mostafa Mohamed Nov 05 '15 at 11:44
  • But dont waste your time there is quasi nothing to block safely and properly your execution until the dfd resolve ! – Anonymous0day Nov 05 '15 at 11:44
  • Then i will not be able to solve it ? i will never get the right value?! i think it's like a bug thing:( – Mostafa Mohamed Nov 05 '15 at 11:45
  • there is a very very vey bad workaround but it is very bad ! but your issue is a design and pattern issue nothing else ! – Anonymous0day Nov 05 '15 at 11:47
  • I fell bad about it i almost waste 2 days in it and i should be end it by now and find out finally it will not work like ever :( ,, Thanks anyway my friend – Mostafa Mohamed Nov 05 '15 at 11:50
  • the very bad way to stop and wait is : `function sleep(ms){ var w; (w = new Date() ).setTime(w.getTime() + ms); while (new Date().getTime() < w.getTime()); }` – Anonymous0day Nov 05 '15 at 11:59
  • instead of calling alert, call sleep(2000) for stoping 2 seconds ! but it is preferable to update your pattern – Anonymous0day Nov 05 '15 at 12:00
  • But be aware that your request could take 5ms like 10 seconds ! it will always ***freeze*** your browser 2 seconds ! – Anonymous0day Nov 05 '15 at 12:02
  • hmmmmmm where should i add this function sleep ? and where i should call it ? if this solution work i will let it now and i will start to workaround again but i need to solve this problem now. – Mostafa Mohamed Nov 05 '15 at 12:12
  • @MostafaMohamed can you test this updated [fiddle](http://jsfiddle.net/gf3qsm24/2/) and tell me what happend ?? – Anonymous0day Nov 05 '15 at 12:18