所以我有两个js文件file1.js
const { expect } = require("chai");
const { createEnrollment } = require("../utils/file2")
describe('create enrollment', function () {
it('enroll the user into the system', async function () {
var x = createEnrollment(inputParams)
console.log(x)
})
File2.js
const fetch = require('node-fetch')
async function createEnrollment(params) {
fetch('URL').then(function (response) {
response.json().then(function (text) {
var val = text;
console.log("VALUE " + val.userId)
return text;
});
module.exports = { createEnrollment }
但是当我运行此代码时,console.log(x)是未定义的,并且在createEnrollment完成之前正在运行。我使函数异步,但返回的值仍未定义。
Fetch是一个异步函数,因此需要与async / await或promise链一起使用。
示例:
async function callAPI(url)
{
let response = await fetch(url);
let data = await response.json()
return data;
}