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:
JavaScript
x
16
16
1
async function uploadMediaInit(fd) {
2
var fHeader = fd.getHeaders();
3
return fd.pipe(concat((data) => {
4
axios({
5
method : 'post',
6
url : 'https://upload.twitter.com/1.1/media/upload.json',
7
data,
8
9
headers: {
10
'content-type' : fHeader['content-type'],
11
Authorization : getAuthorization('POST','https://upload.twitter.com/1.1/media/upload.json',{},"top-secret","top-secret")
12
}
13
})
14
15
}))}
16
Something like “response = await uploadMediaInit(exampleFormData)” returns a ConcatStream object.
How can I acquire the axios response?
Advertisement
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.
JavaScript
1
18
18
1
function uploadMediaInit(fd) {
2
var fHeader = fd.getHeaders();
3
return new Promise(resolve => {
4
fd.pipe(concat(async (data) => {
5
const response = await axios({
6
method: 'post',
7
url: 'https://upload.twitter.com/1.1/media/upload.json',
8
data,
9
headers: {
10
'content-type': fHeader['content-type'],
11
Authorization: getAuthorization('POST', 'https://upload.twitter.com/1.1/media/upload.json', {}, "top-secret", "top-secret")
12
}
13
});
14
resolve(response);
15
}));
16
});
17
}
18