可能未经处理的承诺拒绝

Possible unhandled promise rejection

本文关键字:承诺 拒绝 处理      更新时间:2023-09-26

我试图拒绝我正在使用的框架(Apollo堆栈)的API文档中解释的承诺,但它没有显示示例,它只是声明如果出现错误,我必须拒绝承诺,当我在没有互联网连接的情况下尝试我的应用程序时,我正试图摆脱令人讨厌的YellowBox消息"警告:可能无法解决的承诺拒绝"。

我的方法实际上是有效的,它进入catch并显示错误消息,但我一直收到烦人的YellowBox消息,这就是我试图解决的问题。

我做的第一件事,如预期的那样,进入catch,但它显示了一条YellowBox消息Warning: Possible unhandled promise rejection...

return client.query({ query: gql`...`, }).then((data) => {
    console.log(data);
    data;
}).catch((error) => {
    console.log(error);
    error;
});

我尝试过的最后一件事:

var promise = new Promise(function(resolve, reject) {
  //async call, client.query(..) "returns a promise that should be rejected
  //if there is an error message..."
  client.query({ query: gql`...`, }).then(({data}) => {
    console.log(data);
    resolve(data);
  }).catch((error) => {
    console.log(error); // goes right here, works.
    reject(error.message);
  });
});
//just trying this out
promise.then((data) => {
  console.log(data);
}).catch((error) => {
  console.log(error); 
});

此外,添加流星标签是因为找不到阿波罗,但这几乎是一样的。

按照答案和评论中的建议尝试更多的东西:

var promise = new Promise(function(resolve, reject) {
  client.query({
    query: gql`...`,
  }).then(({data}) => {
    console.log(data);
    resolve(data);
  }).catch((error) => {
    reject(error.message);
  });
}, (error) => {
  console.log(error);
});

另一个:

var callback = {
  success: function(data) {
    console.log("SUCCESS");
  },
  error: function(data) {
    console.log("ERROR");
  }
};
var promise = new Promise(function(resolve, reject) {
  client.query({
    query: gql`...`,
  }).then(({data}) => {
    console.log(data);
    resolve(data);
  }).catch((error) => {
    console.log(error);
    reject(error.message);
  });
  return promise;
});
promise.then(callback.success, callback.error);

另一个:

client.query({
  query: gql`...`,
}).then(({data}) => {
  console.log(data);
}, (error) => {
  console.log(error);
});

ApoloStack:http://docs.apollostack.com/apollo-client/network.html它说,这会返回一个承诺,如果出现错误,该承诺将被拒绝。

YellowBox检测未处理的承诺和诸如此类的事情,并发出警告。

如果client.query为您创建promise,就没有理由创建它。。。

// no new Promise here, just make the query
return client.query({ query: gql`...`, }).then((data) => {
    console.log(data);
    data;
}).catch((error) => {
    console.log(error);
    error;
});

发现了这个问题,框架目前正在处理它,很快就会得到修复,所以目前还没有正确的答案。

我将以正确的方式复制粘贴(如问题所示)。它也是从官方框架的文档中复制的,展示了如何做到这一点,所以下一个遇到同样问题的人会知道他们必须等待几天才能解决。

client.query({ query: gql`...`, }).then((data) => {
    console.log(data);
}).catch((error) => {
    console.log(error);
});

尝试处理拒绝回调中的错误,而不是捕获回调:

var promise = new Promise(function(resolve, reject) {
    client.query({ query: gql`...`, }).then(({data}) => {
        console.log(data);
        resolve(data);
    }, (error)=>{
        console.log(error); // goes right here, works.
        reject(error.message);
    })
 });