Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/386.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Javascript中的函数导出变量_Javascript_Html_Function_Api_Variables - Fatal编程技术网

从Javascript中的函数导出变量

从Javascript中的函数导出变量,javascript,html,function,api,variables,Javascript,Html,Function,Api,Variables,我所要做的就是使用userId变量的值来使用任何东西 async function getMyData(){ const token = ''; spotifyApi.setAccessToken(token); const data = await spotifyApi.getMe(); let userId = data.body.id; return userId; } const userId = getMyData(); conso

我所要做的就是使用userId变量的值来使用任何东西

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)

log(userId)告诉我:{Promise对于任何
async
函数,不要忘记在函数执行之前使用
wait


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

    return userId;
}

/// ./otherFile.js

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

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


您正在代码中使用异步等待功能

因此,getMyData的返回类型实际上是Promise对象。

现在,您可以在另一个文件中使用函数,而不必使用
wait
关键字

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

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

因为我将把getMyData函数导出到另一个.js文件,然后我将运行getMyData来了解用户的spotify id。“module.exports=getMyData()”如果workvar getMyData=require('getMyData'))| | | console.log(getMyData)| | | results:{promise}(它也不起作用)因为函数是异步的,所以使用await getMyData()当我使用await getMyData()时,结果是:“SyntaxError:await仅在异步函数和顶级模块体中有效”):当我尝试您的代码时,这是错误的:(SyntaxError:await仅在异步函数和顶级模块体中有效)@questiontoansw,因为您应该调用此
await getMyData()
也在异步范围内