그래서 두 개의 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가 완료되기 전에 실행됩니다. 함수를 비동기로 만들었지 만 여전히 반환되는 값은 정의되지 않았습니다.
함수 내부에 무언가를 async
하지 않는 것처럼 선언 할 필요가 없습니다 await
.
비동기 함수가 해결 될 때까지 기다려야합니다. 이를 수행하려면 (비동기 / 대기없이) 약속이 해결 될 때까지 기다릴 수있는 액세스 권한이 있어야합니다. 따라서 createEnrollment
메서드 에서 promise를 반환해야합니다 .
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 / 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);
});
});
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다