Search code examples
javascriptasynchronousasync-awaites6-promise

issue with promise Node.js


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!


Solution

  • 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