questiontoansw
questiontoansw

Reputation: 357

Export a variable from a function in Javascript

All I want is take userId variable's value to use anything.

async function getMyData(){
    const token = '';
    spotifyApi.setAccessToken(token);
    
    const data = await spotifyApi.getMe();
    let userId = data.body.id;

    return userId;
}

const userId = getMyData();
console.log(userId)

console.log(userId) saying me this: {Promise <pending<}

Upvotes: 2

Views: 1181

Answers (2)

Mak
Mak

Reputation: 20453

With any async functions, don't forget to use await before function execution


/// ./getMyData.js
export async function getMyData(){
    // ...

    return userId;
}

/// ./otherFile.js

import {getMyData} from './getMyData.js'

(async function () {
   const userId = await getMyData();
   console.log(userId)
})()

Upvotes: 3

Nisanth Reddy
Nisanth Reddy

Reputation: 6395

you are using async await features in your code.

Thus the return type of your getMyData would actually be a Promise object. More about Promises here

Now, heres how you can use your function in another file without having to use the await keyword.

import { getMyData } from '%your file path%';

getMyData().then(function(userId) {
   // use the value of userId here
   console.log(userId);
}

Upvotes: 2

Related Questions