简体   繁体   English

我想从这个 promise 得到 json,我该怎么做

[英]i want get json from this promise, how can i do that

var url = "https://www.metaweather.com/api/location/2471217/#";
let promise = new Promise((resolve, reject) => {
    fetch(url)
        .then(function (response) {
            return response.json();
        }
        )
        .then(function (json) {
            resolve(JSON.stringify(json))
        })

})

promise.then((message) => {
    console.log(message)
}).catch((message) => {
    console.log(message)
})

I want to get json as string.我想获得 json 作为字符串。 thank you guys感谢你们

ps I am a newbie for JS ps我是JS的新手

fetch already returns a promise. There is no need to use the Promise constructor. fetch已经返回 promise。无需使用Promise构造函数。 If you want to get the response as text then you can just call response.text() , not response.json() :如果你想获得文本形式的响应,那么你可以只调用response.text() ,而不是response.json()

fetch(url)
  .then(response => response.text())
  .then(message => console.log(message))
  .catch(error => console.error(error))

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

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