Javascript 函数返回的API响应返回未定义的
所以我有两个js文件 file1.js File2.jsJavascript 函数返回的API响应返回未定义的,javascript,mocha.js,chai,Javascript,Mocha.js,Chai,所以我有两个js文件 file1.js 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
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 }
但是当我运行这个代码控制台时,log(x)是未定义的,并且在createEnrollment完成之前运行。
我将函数设置为异步,但返回的值仍未定义。Fetch是一个异步函数,因此需要与异步/等待或承诺链接一起使用 例如:
async function callAPI(url)
{
let response = await fetch(url);
let data = await response.json()
return data;
}
如果您没有等待函数中的某些内容,则无需将函数声明为
async
您必须等待异步函数解析。为了做到这一点(不使用async/await),您需要访问promise以等待其解决。因此,您需要在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;
});
现在在测试中,您可以等待承诺得到解决:
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 function createEnrollment(params) {
const response = await fetch('URL');
const text = await response.json();
return text;
}
谢谢你的详细回答。这有助于我更清楚地理解这个概念
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);
});
});