【问题标题】:Get Request should return stringify value and assign to a variable获取请求应返回字符串化值并分配给变量
【发布时间】:2021-10-12 11:40:11
【问题描述】:

这是我的方法:

function RequestGet(options, url){
    fetch(url, options).then(function(response){
        return response.json();
    }).then(function(value) {
        data = JSON.stringify(value)
        console.log(data)
    }).catch(function() {
        console.log("fail")
    })
}


function GetUUID(){
    data = RequestGet()
    uuid = []
    data2 = data.results[0].groups
    groupLength = data2.length
    for (i = 0; i < groupLength; i++){
        uuid[i] = data2[i].uuid
    }
    uuidString = uuid.toString()
    console.log(uuidString)
}

我需要 RequestGet 来返回 'data' 的输出(我可以使用 console.log(data) 查看),所以我可以使用下面的 GetUUID 函数中的字典来获取特定的键(键 I' m 寻找的是 uuid)。

我只需要能够将 GET 响应传递给 GetUUID 方法。

目前它返回“未定义”

谢谢。

【问题讨论】:

  • 你没有从 RequestGet 返回任何东西。
  • 这也不起作用。 function RapidproGet(options, url){ return fetch(url, options).then(function(response){ return response.json(); }).then(function(value) { data = JSON.stringify(value) //console.log(data) return data; }).catch(function() { //console.log("fail") }) }

标签: javascript node.js get


【解决方案1】:

您需要从您的RequestGet 返回一个 Promise。试试这个:

function RequestGet(options, url){
   return fetch(url, options).then(function(response){
        return response.json();
    }).then(function(value) {
        data = JSON.stringify(value)
        console.log(data)
        return data;
    }).catch(function() {
        console.log("fail")
    })
}


async function GetUUID(){
    data = await RequestGet()
    uuid = []
    data2 = data.results[0].groups
    groupLength = data2.length
    for (i = 0; i < groupLength; i++){
        uuid[i] = data2[i].uuid
    }
    uuidString = uuid.toString()
    console.log(uuidString)
}

【讨论】:

  • 感谢您的评论,但它似乎不起作用。 ``` function RequestGet(options, url){ return fetch(url, options).then(function(response){ return response.json(); }).then(function(value) { data = JSON.stringify(value ) //console.log(data) return data; }).catch(function() { //console.log("fail") }) } async function GetUUID(){ data = await RequestGet() console.log( data) } RequestGet(options, url) GetUUID() 输出:未定义 ``` 如果我取消注释 console.log(data),我可以看到字典
  • 您在哪里声明了datauuid 等?全球范围内?
  • 目前我已经把它拿出来了,直到我能够将响应传递给 UUID 方法。所以我只有这个:function RequestGet(options, url){ return fetch(url, options).then(function(response){ return response.json(); }).then(function(value) { data = JSON.stringify(value) //console.log(data) return data; }).catch(function() { //console.log("fail") }) }async function GetUUID(){ data = await RequestGet() console.log(data) }
  • async function GetUUID(){ data = await RequestGet() console.log(data) }
  • 试试这个简化:async function RequestGet(options, url){ const response = await fetch(url, options); const data = await response.json(); return data; }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多