Getting the Axios response from inside the pipe function in javascript

Tags: ,



Hello right now I am trying to upload media to Twitter via API and for that I need a value from a previous axios call.

This is my API call which inits the media upload:

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")
      }
    })
    
  }))}

Something like “response = await uploadMediaInit(exampleFormData)” returns a ConcatStream object.
How can I acquire the axios response?

Answer

Wrap a Promise around the fd.pipe method and return it from the function. This way you can resolve the promise whenever your axios request has completed.

Inside the concat function use async / await to await the axios request to get a response. Then resolve the promise with the response gotten from the request and your value will be available outside of the function.

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);
    }));
  });
}


Source: stackoverflow