【问题标题】:how to resolve a response multiple times如何多次解决响应
【发布时间】:2021-07-30 12:33:02
【问题描述】:

所以我有一个返回值的函数 例如:

let  value= function () =>{
//basically getting values from an api 

let get = axios.get("example.com").then(res=>{
Value = res
})
//     Value is the value that had been retrieved from a  Get request from an API 
return Value ; 

}
module.export = {value}

^^ 那是第二个文件中的第一个文件,我想获取使用它们的值,这里的问题是我第一次使用该函数:

const first_file = require("./first_file") 

first_file.then(res=>{
console.log(res)
})

我第一次使用该函数时会很好,但有时如果出现错误,我会使用 try catch 方法再次调用该函数,这将返回我第一次得到的相同响应

对不起,不好的解释

【问题讨论】:

  • 我认为您只需导出get,然后执行类似first_file.then(res => ..., err => ...); 之类的操作。
  • 你好,所以当另一个函数发生错误时,我正在召回该函数,谢谢

标签: javascript node.js async-await promise


【解决方案1】:

我不确定你想要什么。但是,如果呼叫崩溃,您可能不应该再这样做了。 但是,如果您想在通话崩溃时做任何事情,您可以在.then 之后使用.catch

编辑您的函数 value 以返回 axios 调用。

let value = function () => {
     return axios.get("example.com")
}

module.export = {value}

然后你可以这样访问它:

const first_file = require("./first_file") 

first_file.value.then(res=>{
    console.log(res)
}).catch(error => {
// For exemple you can log the error, or do whatever you want here
   console.log(error) 
})

【讨论】:

  • 嗨,谢谢您在发生错误时的回答(不是来自函数) ,抱歉不清楚
  • 得到相同的答案是正常的。如果您调用例如http://i-do-not-exist.zut,然后您尝试重新调用.catch 中的相同地址,例如它仍然不会退出并且仍然具有与404 相同的状态。我的意思是如果您有错误您的后端或 url 并尝试在 catch 中调用相同的 url,您仍然会遇到相同的错误
  • 当我回想起函数时,错误不会来自 GET url,这将是另一回事,但是谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-07
  • 2013-05-11
  • 2021-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多