API 来自函数 return 的响应 return 未定义
API response return from a function returns undefined
所以我有两个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 完成之前 运行ning。 我使函数异步,但返回的值仍然未定义。
Fetch 是一个异步函数,因此需要与 async/await 或 promise 链一起使用。
示例:
async function callAPI(url)
{
let response = await fetch(url);
let data = await response.json()
return data;
}
如果您没有在其中 await
构建函数,则无需将函数声明为 async
。
您必须等待异步函数解析。为了做到这一点(没有 async/await),您需要访问承诺以等待它解决。因此,您需要 return createEnrollment
方法中的承诺:
function createEnrollment(params) {
// Note the return before the fetch!
return fetch('URL')
.then(function(response) {
return response.json();
})
.then(function(text) {
var val = text;
console.log("VALUE " + val.userId)
return text;
});
现在在你的测试中,你可以等待 promise 被解决:
describe('create enrollment', function () {
it('enroll the user into the system', function () {
// The return here is intended for the test to wait until the promise is fullfilled.
return createEnrollment(inputParams).then(function(x) {
console.log(x);
});
});
});
或者,如果您使用 async/await 语法:
async function createEnrollment(params) {
const response = await fetch('URL');
const text = await response.json();
return text;
}
describe('create enrollment', function () {
it('enroll the user into the system', async function () {
const x = await createEnrollment(inputParams);
});
});