I have been trying to figure this out for quite some time and it's too confusing so i thought i'd ask.
var listenKey = ""; const createListenKey = async () => { await axios({ url: "/api/v3/userDataStream", method: "POST", baseURL: "https://api.binance.com", headers: { "X-MBX-APIKEY": "H48w9CLuTtTi955qWjcjjEKhh0Ogb3jnnluYucXXXXXXXXXXXXXXXX", }, }).then((response) => { var key = response.data.listenKey; console.log(key, "created"); return key; }); }; listenKey = createListenKey(); listenKey.then((key) => { console.log(key); });
the console.log in the last but one line is printing undefined. Why is that?
Thanks in advance!
You did not return anything from the async function createListenKey
const asynF = async ()=>{
Promise.resolve(1).then(res=>{
//Simulating response from axios call
console.log(res)
})
// you are not returning anyting from this function equivalent of => return ;
}
asynF().then(res=>{
//this would log undefined
console.log(res)
})
As you know async function returns a promise you have two options make the outer wrapper a async function as well and just use await like below
const key = await createListenKey(config)
or else
you could simply do this
return createListenKey(config).then(res=>{
listenKey = res
})
can't say much more without knowing context. Might I suggest not to mix then and async wait together
Because the createListenKey()
function doesn't return anything. The return statement in the then clause inside that function is scoped in the then block. To return a value from an async function, you need to do something like this.
const createListenKey = async () => {
const response = await axios({
url: "/api/v3/userDataStream",
method: "POST",
baseURL: "https://api.binance.com",
headers: {
"X-MBX-APIKEY":
"H48w9CLuTtTi955qWjcjjEKhh0Ogb3jnnluYucXXXXXXXXXXXXXXXX",
},
})
var key = response.data.listenKey;
console.log(key, "created");
return key;
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.