繁体   English   中英

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

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

我认为至少有一个问题是代码的其余部分正在处理,而函数仍在运行。 这里有一些充实的代码来显示问题。 第一个块位于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;                
            });
        }
    });
});

不能退货 ,它是异步的。 但是,您可以返回您已经使用的承诺:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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