获取Promise永远不会被执行

时间:2016-03-15 08:18:23

标签: promise nativescript fetch-api

我使用nativescript为android开发应用程序。 我有类似

的东西
var fetchModule = require("fetch");
fetchModule.fetch("http://202.120.227.11/")
    .then(function(resp){
        console.log(JSON.stringify(resp));
        return resp;
    })
    .catch(function(err){
        console.log(JSON.stringify(err));
        return err;
    });

then块永远不会被执行。 有时,catch块会被执行并产生网络错误。 但无论哪种情况,都会发送请求,并根据我的tcpdump记录顺利接收响应。

因此,似乎nativescript已经因某种原因过滤了响应。

有人经历过吗?

2 个答案:

答案 0 :(得分:4)

请注意,您的respResponse对象,如果您想要阅读其内容,则需要使用其中一项功能:arrayBufferblob,{{ 3}},formDatajson

这些函数读取对完成的响应,并返回一个以读取值解析的promise。

例如,

fetch("http://202.120.227.11/")
.then(function(resp){
  return resp.json();
})
.then(function(val) {
  console.log(JSON.stringify(val));
  return val;
});

答案 1 :(得分:0)

我知道这已经太晚了,但我只想发布任何人遇到同样的问题。我遇到了与NativeScript相同的问题,我的解决方案是保护我的站点/端点。 App Transport Security策略要求使用安全连接。因此,http将无法正常工作。您必须通过https连接。