承诺在回调函数中

时间:2018-01-30 14:17:50

标签: javascript asynchronous

我只是想知道每次调用回调函数时这个回调中的promise是否会运行?

  request.post({
    headers: { 'content-type': 'text/xml', 
      SOAPAction: 'http://tempuri.org/enquireFines' 
    },
    url: meta.URL,
    body: requestBody
  }, (error, response, body) => {
    apiLogs.update({
      Response: body,
      Status: 'SUCCESS'
  }, { 
  where: { 
      TransactionId: meta.TRANSACTIONID 
  }}).then(() => {});

1 个答案:

答案 0 :(得分:2)

您可以使用new Promise将经典回调API转换为承诺。要将任何请求回调函数转换为承诺,您可以执行以下操作:

const requestAsPromise = request => fn => args =>
  new Promise(
    (resolve,reject)=>
      fn.apply(
        request,
        args.concat([
          (error, response, body) =>
            (error)
              ? rejct(error)
              : resolve([response,body])
        ])
      )
  );

以下是如何使用它:

  requestAsPromise(request)(request.post)([
    {
      headers: { 'content-type': 'text/xml', 
        SOAPAction: 'http://tempuri.org/enquireFines' 
      },
      url: meta.URL,
      body: requestBody
    }    
  ])
  .then(
    ([response,body])=>
      apiLogs.update(
        {
          Response: body,
          Status: 'SUCCESS'
        }, 
        { 
          where: { 
            TransactionId: meta.TRANSACTIONID 
          }
        }
      )
  )
  .then(
    dbResolve=>console.log("Finished, db returned:",dbResolve)
  )
  .catch(
    err=>console.error("Something went wrong:",err)
  );

如果request.post已经返回一个promise(您必须检查,我不确定您使用的是什么),那么您不需要将回调传递给request.post,而是直接使用它的承诺:

request.post(
  {
    headers: { 'content-type': 'text/xml', 
      SOAPAction: 'http://tempuri.org/enquireFines' 
    },
    url: meta.URL,
    body: requestBody
  }    
)
.then(
  ([response,body])=>
    apiLogs.update(
      {
        Response: body,
        Status: 'SUCCESS'
      }, 
      { 
        where: { 
          TransactionId: meta.TRANSACTIONID 
        }
      }
    )
)
.then(
  dbResolve=>console.log("Finished, db returned:",dbResolve)
)
.catch(
  err=>console.error("Something went wrong:",err)
);