繁体   English   中英

从 javascript 中的管道函数内部获取 Axios 响应

[英]Getting the Axios response from inside the pipe function in javascript

您好,现在我正在尝试通过 API 将媒体上传到 Twitter,为此我需要一个来自先前 axios 调用的值。

这是我启动媒体上传的 API 调用:

async function uploadMediaInit(fd) {
  var fHeader = fd.getHeaders();
  return fd.pipe(concat((data) => {
    axios({
      method : 'post',
      url : 'https://upload.twitter.com/1.1/media/upload.json', 
      data,
      
      headers: {
        'content-type' : fHeader['content-type'],
        Authorization : getAuthorization('POST','https://upload.twitter.com/1.1/media/upload.json',{},"top-secret","top-secret")
      }
    })
    
  }))}

类似“response = await uploadMediaInit(exampleFormData)”的东西会返回一个 ConcatStream 对象。
如何获取 axios 响应?

fd.pipe方法周围包裹一个Promise并从函数中返回它。 这样你就可以在 axios 请求完成时解决承诺。

concat函数内部,使用async / await等待 axios 请求以获取响应。 然后使用从请求中获得的响应来解决承诺,您的值将在函数之外可用。

function uploadMediaInit(fd) {
  var fHeader = fd.getHeaders();
  return new Promise(resolve => {
    fd.pipe(concat(async (data) => {
      const response = await axios({
        method: 'post',
        url: 'https://upload.twitter.com/1.1/media/upload.json',
        data,
        headers: {
          'content-type': fHeader['content-type'],
          Authorization: getAuthorization('POST', 'https://upload.twitter.com/1.1/media/upload.json', {}, "top-secret", "top-secret")
        }
      });
      resolve(response);
    }));
  });
}

暂无
暂无

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

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