简体   繁体   中英

How can I return a value using request.get().then in Dojo for JavaScript?

I think at least one of the problems is that the rest of the code is processing while the function is still running. Here is some fleshed out code to show the problem. The first block is in an HTML file and uses load.js.

require(["load.js"], function(loader) {
    var load = new loader("fileLoad", "myID");
    var theString = load.loadFromDB();
    alert(theString);
});

With this code the variable 'theString' does not receive the returned value before the alert is called.

Here is the code from load.js:

define(["dojo/_base/declare", "dojo/request/xhr", "dojo/request"]
        , function(declare, xhr, request) {            

    return declare(null, {
        constructor: function(/*string*/ action, /*string*/ id) {
            this.action = action;
            this.id = id;
        },
        loadFromDB: function() {
            request.get("../../author-load-save.php", {
                query: {
                    action: this.action,
                    id: this.id
                }
            }).then(function(text) {
                console.log("The server returned: \n", text);                
                return text;                
            });
        }
    });
});

You cannot return it , it's asynchronous. You can however return the promise that you are already using:

require(["load.js"], function(loader) {
    var load = new loader("fileLoad", "myID");
    load.loadFromDB().then(alert); // alert is a function that takes theString
});

define(["dojo/_base/declare", "dojo/request/xhr", "dojo/request"]
        , function(declare, xhr, request) {            

    return declare(null, {
        constructor: function(/*string*/ action, /*string*/ id) {
            this.action = action;
            this.id = id;
        },
        loadFromDB: function() {
            return request.get("../../author-load-save.php", {
//          ^^^^^^^
                query: {
                    action: this.action,
                    id: this.id
                }
            }).then(function(text) {
                console.log("The server returned: \n", text);                
                return text; 
            }); // makes a promise for the text
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM