2

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

5
  • Because I will export getMyData function to another .js file and then i will run getMyData to learn user's spotify id. Commented May 10, 2021 at 20:23
  • "module.exports = getMyData()" should work Commented May 10, 2021 at 20:23
  • var getMyData = require('getMyData') ||||||| console.log(getMyData) |||| results: {promise <pending>} (it didnt work too) Commented May 10, 2021 at 20:27
  • its because the function is async, use await getMyData() Commented May 10, 2021 at 20:29
  • when i use await getMyData() results are saying: "SyntaxError: await is only valid in async functions and the top level bodies of modules" ): Commented May 10, 2021 at 20:31

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

This is error when i try your code : (SyntaxError: await is only valid in async functions and the top level bodies of modules)
@questiontoansw because you should call this await getMyData() also in async scope
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.