简体   繁体   English

Promise 保持挂起状态,“then”或“catch”未触发。 ReactJS

[英]Promise keeps pending and “then” or “catch” are not triggering. ReactJS

I'm catching up to learn React.我正在赶上学习 React。 If you have any tips on this code, please share, it is very important to me:).如果您对此代码有任何提示,请分享,这对我很重要:)。

Why this promise doesn't work?为什么这个 promise 不起作用?

In console show status pending.在控制台中显示状态待定。

The promise: promise:

_server.get(`/select`, (req, res) => {   
        return DefaultSQL.select(table).then((result) => {           
            return result
        }).catch((err) => {
            console.log(err)
        });      
})

Where I call the promise:我称之为 promise 的地方:

export const getData = (url) => {
  const response =  Server.get(url)       status
    return response.then((result) => {    // <- Not firing  
      return result 
  }).catch((err) => { // <- Not firing too
    console.log(err);
  })    
}

What the promise call: promise 叫什么:

class DefaultSQL {
  select(table) {
    const sql = `SELECT * FROM ${table}`;
    return Db.conn.query(sql).then((result) => 
      result
    ).catch((err) => {  
      console.log(err) 
    });
  }
...

EDIT:编辑:

When I change the "return result" to "return res.json(result)" the promise does not keep pending, but where I call the promise gets a error saying that "response" is not a function当我将“返回结果”更改为“返回 res.json(结果)”时,promise 不会保持挂起状态,但是在我调用 promise 的地方会收到错误消息,指出“响应”不是 ZC1C425268E68385D1ABZ5074FC

You should rethrow the error/throw a new error to catch error again .您应该rethrow the error/throw a new errorcatch error again

It's an example:这是一个例子:

 Promise.reject("throwed on demo 1").catch((e) => { console.log("Catched", e) }).catch((e) => { // unreached block console.log("Can NOT recatch", e) }) Promise.reject("throwed on demo 2").catch((e) => { console.log("Catched", e) throw e }).catch((e) => { console.log("Recatched", e) })

UPDATE: Another issue, you need to send a response even error/success.更新:另一个问题,即使错误/成功,您也需要发送响应。 Otherwise, the request will not respond, the client will be pending forever.否则,请求将不会响应,客户端将永远挂起。

_server.get(`/select`, (req, res) => {   
        return DefaultSQL.select(table).then((result) => {           
            res.send(result)
            //return result
        }).catch((err) => {
            res.status(500).send(err)
            console.log(err)
        });      
})

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

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