如何使用request.get()返回值,然后在Dojo for JavaScript中?

时间:2014-01-07 22:03:53

标签: javascript dojo

我认为至少有一个问题是代码的其余部分正在处理,而函数仍在运行。这里有一些充实的代码来显示问题。第一个块位于HTML文件中并使用load.js。

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

使用此代码变量' theString'在调用警报之前不会收到返回的值。

以下是来自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;                
            });
        }
    });
});

1 个答案:

答案 0 :(得分:2)

cannot return it,它是异步的。但是,您可以返回您已经使用的承诺:

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
        }
    });
});