javascript - Vue.js 无法将数据从获取请求中获取到变量中

标签 javascript vue.js request-promise

<分区>

我正在运行一个为 Vue.js 应用程序提供服务的服务器。 所以如果我输入 http://localhost:9999/进入我的浏览器, 浏览器获取 4 个重要文件: post.js、get.js、vue.js 和带有 vue 代码的 index.HTML。

我得到了一个动态有序列表来工作,其中每个列表元素 有一个按钮来添加一个元素并删除它自己以及 将一些变量输出到控制台的调试按钮。

现在我需要向我的服务器发出获取请求以获取包含 JSON 数据的数组 这将在第二个有序列表中创建一些元素。

我尝试了以下但没有任何效果:

//get("http://localhost:9999/text/1", inputData)
//get("http://localhost:9999/text/1").then(inputData)
//inputData = get("http://localhost:9999/text/1")

这是get.js的内容:

//which is correctly included in the vue.js index.HTML
//<script SRC="get.js"> </script>
function get(url, params) {
        // Return a new promise.
        return new Promise(function(resolve, reject) {
            // Do the usual XHR stuff
            var req = new XMLHttpRequest();
            req.open('GET', url, true);
        req.setRequestHeader('Content-type', 'application/json');

            req.onload = function() {
                // This is called even on 404 etc
                // so check the status
                if (req.status == 200) {
                    // Resolve the promise with the response text
                    //resolve(req.response);
                    resolve(JSON.parse(req.response));
            }
            else {
                // Otherwise reject with the status text
                // which will hopefully be a meaningful error
                reject(req.statusText);
            }
        };

        // Handle network errors
        req.onerror = function() {
            reject("Network Error");
        };

        // Make the request
        req.send(params);
    });
}

在我调用的 vue.js 方法 block 之后

mounted() {
    this.$nextTick(function () {
    var inputData=[]
    //get("http://localhost:9999/text/1", inputData)
    //get("http://localhost:9999/text/1").then(inputData)
    inputData = get("http://localhost:9999/text/1")
    app.vueData = inputData
    console.log(inputData)
    console.log(JSON.stringify(inputData))
    console.log(';)')
    })
}

Promise 有内容,但我无法将其传输到变量。

Promise {<pending>}
__proto__: Promise
catch: ƒ catch()
constructor: ƒ Promise()
finally: ƒ finally()
then: ƒ then()
Symbol(Symbol.toStringTag): "Promise"
__proto__: Object
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Array(4)
0: {text: "This List"}
1: {text: "was pulled"}
2: {text: "from the"}
3: {text: "server"}
length: 4
__proto__: Array(0)

由于评论被删除,我必须发挥创意:

@Apal Shah 感谢您的回答。您的代码看起来比 then() 解决方案好得多。 在阅读您的解决方案之前,我通过添加大量 console.log()s 了解了罪魁祸首

console.log('app.vueData vor app.vueData = inputData: ')
console.log(app.vueData)

app.vueData = inputData

console.log('inputData nach Zuweisung: ')
console.log(inputData)

console.log('JSON.stringify(inputData)')
console.log(JSON.stringify(inputData))

console.log(';)')

控制台输出:

get block:                                                                  (index):153
app.vueData vor app.vueData = inputData:                                    (index):156
 [__ob__: Observer]                                                         (index):157
  length: 0
  __ob__: Observer {value: Array(0), dep: Dep, vmCount: 0}
  __proto__: Array
inputData nach Zuweisung:                                                   (index):161
 [__ob__: Observer]                                                         (index):162
  length: 0
  __ob__: Observer {value: Array(0), dep: Dep, vmCount: 0}
  __proto__: Array
 JSON.stringify(inputData)                                                  (index):164
 []                                                                         (index):165
 ;)                                                                         (index):167

 Download the Vue Devtools extension for a better development experience:   vue.js:9049
 https://github.com/vuejs/vue-devtools

 You are running Vue in development mode.                   vue.js:9058
 Make sure to turn on production mode when deploying for production.
 See more tips at https://vuejs.org/guide/deployment.html

 (4) [{…}, {…}, {…}, {…}]                                                   (index):154
  0: {text: "This List"}
  1: {text: "was pulled"}
  2: {text: "from the"}
  3: {text: "server"}
  length: 4
  __proto__: Array(0)

感谢大家现在就去测试它。

解决方法是:

mounted() {
    this.$nextTick(async function () {

        console.log('get block: ')
        console.log('app.vueData vor app.vueData = get() ')
        console.log(app.vueData)

        //Get is a deferred / asynchronous process / operation
        app.vueData = await get("http://localhost:9999/text/1")

        console.log('app.vueData nach Zuweisung: ')
        console.log(app.vueData)

        console.log('JSON.stringify(app.vueData)')
        console.log(JSON.stringify(app.vueData))
        })

        console.log(';)')
}

需要注意的是 async 必须在未安装的函数或 this.$nextTick 之前。

最佳答案

您已经创建了一个在 HTTP 请求完成后解析数据的 Promise,但您的代码并未等待此 Promise 解析。

你可以做两件事:
1. 使用.then()
2. 使用async/await(我更喜欢这个,因为它看起来很干净)

如果你想使用async/await,

mounted() {
    this.$nextTick(async function () {
    var inputData=[]
    //get("http://localhost:9999/text/1", inputData)
    //get("http://localhost:9999/text/1").then(inputData)
    inputData = await get("http://localhost:9999/text/1")
    app.vueData = inputData
    console.log(inputData)
    console.log(JSON.stringify(inputData))
    console.log(';)')
    })
}

在这段代码中,您可以看到 this.$nextTick 中的函数前有 async 关键字和 get 前有 await 关键字方法。

如果你想处理错误,你总是可以使用 try/catch block 。

try {
  inputData = await get("http://localhost:9999/text/1");
} catch (e) {
  console.log(e);
}

如果您是 .then() 的粉丝,您的 mounted 方法将如下所示,

mounted() {
    this.$nextTick(function () {
    var inputData=[]
    get("http://localhost:9999/text/1").then(inputData => {
      app.vueData = inputData
      console.log(inputData)
      console.log(JSON.stringify(inputData))
    });
    console.log(';)')
    })
}

关于javascript - Vue.js 无法将数据从获取请求中获取到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57078453/

相关文章:

Javascript:当鼠标悬停在一个元素上时,如何定位幻灯片中选定的元素?

php - AJAX调用成功但抛出未定义索引错误

javascript - 停止 OpenLayers 2 中的事件?

javascript - 使用 Next.js react onClick 事件处理程序不工作

javascript - 从数据库中删除会引发请求失败,状态代码为 405 错误

node.js catch block 在等待时未按预期触发

javascript - Nuxt JS 中的基本身份验证

php - 如果值为 true,则为每个项目添加类

node.js - NodeJS 请求 promise ERR_TLS_CERT_ALTNAME_INVALID

node.js - AWS S3 - 以八位字节流的形式获取 PDF 并上传到 S3 存储桶