【问题标题】:how to run a function inside function asynchronously? [duplicate]如何异步运行函数内部的函数? [复制]
【发布时间】:2021-12-31 07:24:18
【问题描述】:

我正在为我的网站制作支付网关,但我的调试器有问题。即使我使用了async await,即使某些特定的行是异步执行的,但是当另一个函数出现时它会运行同步。为了更好地理解,请查看下面提到的实际代码

这是我的 app.js 文件

app.post('/pay', 异步函数(req,res){

let response = await orderApi.pay(req.body)  // First debugger goes here (1)
res.json(response)  // (need this line to be executed when pay function is completed) (4)
console.log(response)

这是我的订单 API 文件

exports.pay = async function (body) {
  var headers = { //then here debugger comes (2)
    'X-Api-Key': 'test_d5f178f6f910a5ec48a429d540d',
    'X-Auth-Token': 'test_f3f32cda3a7aafc2a188579530f'
  }
 

  var payload = {
    purpose: body.purpose,
    amount: body.amount,
    phone: body.phone,
    buyer_name: body.buyer_name, 
   
  }
  request.post('https://test.instamojo.com/api/1.1/payment-requests/', { form: payload, headers: headers }, function (error, response) { // (3) !!!
       var parsed = JSON.parse(response.body); // then it does not goes here then it goes back in app.js file (5)
      var redirectu = parsed.payment_request.longurl (6)
      return redirectu
   
  })
}

我无法理解是什么问题请帮我解决 // 记住 (1),(2).. 之类的点,它们是我的调试器所在的数字

【问题讨论】:

  • 我需要使用回调吗
  • 你的问题是什么?

标签: node.js asynchronous async-await instamojo


【解决方案1】:

您可能希望返回从 request.post 返回的内容,这意味着我们应该将代码修改为如下所示:

const response = await request.post('https://test.instamojo.com/api/1.1/payment-requests/', { form: payload, headers: headers });
const parsed = JSON.parse(response.body);
const redirectu = parsed.payment_request.longurl(6);
return redirect;

说明

request.post 的回调中的return 在函数执行完成后返回,并且由于外部函数中没有显式返回,它只是调用request.post 并(隐式)返回undefined 而无需等待request.post 完成执行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多