wait는 비동기 기능에서만 유효합니다.
나는 이 코드를 에 썼다.lib/helper.js
:
var myfunction = async function(x,y) {
....
return [variableA, variableB]
}
exports.myfunction = myfunction;
그런 다음 다른 파일에서 사용하려고 했습니다.
var helper = require('./helper.js');
var start = function(a,b){
....
const result = await helper.myfunction('test','test');
}
exports.start = start;
오류가 발생했습니다.
await is only valid in async function
뭐가 문제죠?
는, 「이러다」를 않습니다.myfunction
, 하하에게는start
.
async function start() {
....
const result = await helper.myfunction('test', 'test');
}
// My function
const myfunction = async function(x, y) {
return [
x,
y,
];
}
// Start function
const start = async function(a, b) {
const result = await myfunction('test', 'test');
console.log(result);
}
// Call start
start();
가 알고 .await
ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ, ㄴ.return await
.
틀렸어
async function myfunction() {
console.log('Inside of myfunction');
}
// Here we wait for the myfunction to finish
// and then returns a promise that'll be waited for aswell
// It's useless to wait the myfunction to finish before to return
// we can simply returns a promise that will be resolved later
// useless async here
async function start() {
// useless await here
return await myfunction();
}
// Call start
(async() => {
console.log('before start');
await start();
console.log('after start');
})();
맞아요.
async function myfunction() {
console.log('Inside of myfunction');
}
// Here we wait for the myfunction to finish
// and then returns a promise that'll be waited for aswell
// It's useless to wait the myfunction to finish before to return
// we can simply returns a promise that will be resolved later
// Also point that we don't use async keyword on the function because
// we can simply returns the promise returned by myfunction
function start() {
return myfunction();
}
// Call start
(async() => {
console.log('before start');
await start();
console.log('after start');
})();
,, 는, 는, 는, 는, 는, 는, 는, 는, 는, 는, 는, 는, 는, 는, 는, 는, 는, 는, 는, 는, 는, 는return await
remitant : ( ) : (try/seturn : (try/seturning)
「」를 await
는 , 「」, 「」로 할 필요가 async
말한 것처럼 '의 본질을 .executing context
「」의 대상이 .await
우선의 과제
★★★★★★★★★★★★★★★★★★★★★★★async
before fn
에는 당신의 '자신의 '자신의' '자신의 '자신의'async
작업이 실행됩니다.
var start = async function(a, b) {
// Your async task will execute with await
await foo()
console.log('I will execute after foo get either resolved/rejected')
}
설명:
'를 '가져오다'라고했습니다.method
, 「」입니다.asynchronous
동시에 실행할 수 있습니다. 이 그 일을 async
은 다른 .execution context
.async
await
.
var helper = require('./helper.js');
var start = async function(a,b){
....
const result = await helper.myfunction('test','test');
}
exports.start = start;
무슨 일이 벌어지는지 궁금해서
await
약속/태스크 메서드/메서드/ 및 '메서드/메서드/메서드'async
기다리다
, 당, 당, 당, 당, also, also, also, also, also, also, alsopromises
,await
약속이나 약속이나 약속이나 약속이나 약속이나 약속이나 같은 과정을 하고 있습니다.을 만들고 하다.resolve
콜백
상세한 것에 대하여는, MDN DOCS 를 참조해 주세요.
이 에러가 발생했을 때, 「async」함수내에 있는 맵 기능에 콜이 있는 것이 판명되었습니다.따라서, 이 에러 메세지는 실제로는, 맵 기능이 「async」라고 마크 되어 있지 않은 것을 나타내고 있습니다.저는 이 문제를 지도 기능에서 "대기" 호출을 제거하고 예상되는 동작을 얻을 수 있는 다른 방법을 생각해냄으로써 해결했습니다.
var myfunction = async function(x,y) {
....
someArray.map(someVariable => { // <- This was the function giving the error
return await someFunction(someVariable);
});
}
같은 문제가 발생했는데 다음 코드 블록에서 같은 오류 메시지가 나타납니다.
repositories.forEach( repo => {
const commits = await getCommits(repo);
displayCommit(commits);
});
문제는 getCommits() 메서드가 비동기인데 Promise에 의해 생성된 인수 repo를 전달하고 있다는 것입니다.그래서 다음과 같이 async(repo)라는 단어를 추가해야 했습니다.그러면 동작하기 시작했습니다.
repositories.forEach( async(repo) => {
const commits = await getCommits(repo);
displayCommit(commits);
});
Chrome Extension을 쓰고 있을 때 루트에서 이 오류가 발생할 경우 다음 "해결책"을 사용하여 수정할 수 있습니다.
async function run() {
// Your async code here
const beers = await fetch("https://api.punkapi.com/v2/beers");
}
run();
를 비동기 코드로 .async function
이치노
의 현재 async
await
는, 「」만을 하고 있습니다.await
의 " " 입니다.async
을 start
하여 " "를 사용할 수 .await
에 inside inside inside start
var start = async function(a, b) {
}
있는await
현재 스테이지 2에 있습니다.https://github.com/tc39/proposal-top-level-await
async/module은 약속을 처리하는 메커니즘입니다.두 가지 방법으로 할 수 있습니다.
functionWhichReturnsPromise()
.then(result => {
console.log(result);
})
.cathc(err => {
console.log(result);
});
또는 wait를 사용하여 먼저 완전히 처리하겠다는 약속을 기다릴 수 있습니다. 즉, 이 약속은 거부되거나 해결됩니다.
함수 내에서 wait(약속 이행 대기)를 사용하려면 컨테이너 함수가 비동기 함수여야 합니다.왜냐하면 비동기적으로 이행하는 약속을 기다리고 있기 때문입니다.| 이치에 맞습니까?
async function getRecipesAw(){
const IDs = await getIds; // returns promise
const recipe = await getRecipe(IDs[2]); // returns promise
return recipe; // returning a promise
}
getRecipesAw().then(result=>{
console.log(result);
}).catch(error=>{
console.log(error);
});
Axios를 사용하는 노드의 HTTP 요청에서 다음 코드를 찾았습니다.
const axios = require('axios')
const getBreeds = async () => {
try {
return await axios.get('https://dog.ceo/api/breeds/list/all')
} catch (error) {
console.error(error)
}
}
const countBreeds = async () => {
const breeds = await getBreeds()
if (breeds.data.message) {
console.log(`Got ${Object.entries(breeds.data.message).length} breeds`)
}
}
countBreeds()
또는 Promise 사용:
const axios = require('axios')
const getBreeds = () => {
try {
return axios.get('https://dog.ceo/api/breeds/list/all')
} catch (error) {
console.error(error)
}
}
const countBreeds = async () => {
const breeds = getBreeds()
.then(response => {
if (response.data.message) {
console.log(
`Got ${Object.entries(response.data.message).length} breeds`
)
}
})
.catch(error => {
console.log(error)
})
}
countBreeds()
foreach 내의 비동기 함수를 호출한 경우 for loop으로 업데이트합니다.
하나의 파일로 실행할 수 있습니다.
비동기적이어야 하는 로컬 함수에 wait only가 적용되는 것 같습니다.
또, 한층 더 복잡한 구조와 다른 파일 사이에 있는 것에 대해서도 고민하고 있습니다.그래서 이렇게 작은 테스트 코드를 만들었어요.
edit: node.js에서 작업하고 있다는 말을 잊어버렸습니다.슬리. 확실한 질문은 없습니다.토론에 도움이 될 것 같아서..
function helper(callback){
function doA(){
var array = ["a ","b ","c "];
var alphabet = "";
return new Promise(function (resolve, reject) {
array.forEach(function(key,index){
alphabet += key;
if (index == array.length - 1){
resolve(alphabet);
};
});
});
};
function doB(){
var a = "well done!";
return a;
};
async function make() {
var alphabet = await doA();
var appreciate = doB();
callback(alphabet+appreciate);
};
make();
};
helper(function(message){
console.log(message);
});
Express의 일반적인 문제:
경고는 함수 또는 호출 위치를 나타낼 수 있습니다.
Express 항목은 다음과 같은 경향이 있습니다.
app.post('/foo', ensureLoggedIn("/join"), (req, res) => {
const facts = await db.lookup(something)
res.redirect('/')
})
점에 주의:=>
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
문제는 실제로 db.lookup 호출이 아니라 바로 여기 Express 항목에 있습니다.
필요조건:
app.post('/foo', ensureLoggedIn("/join"), async function (req, res) {
const facts = await db.lookup(something)
res.redirect('/')
})
'를 'nix'로 합니다.=>
async function
.
"비동기 함수에서만 유효"
하지만 왜 그랬을까?「synchronous」는 비동기 콜을 명시적으로 동기 콜로 변환합니다.따라서 발신자는 비동기(또는 비동기)일 수 없습니다.최소한, 콜이 「synchronous」로 발신되었기 때문은 아닙니다.
네, wait / async는 훌륭한 개념이었지만 구현이 완전히 중단되었습니다.
어떤 이유로든 wait 키워드는 비동기 방식 내에서만 사용할 수 있도록 구현되어 있습니다.이것은 실제로는 버그입니다만, 여기 이외에는 어디에서도 볼 수 없습니다.이 오류의 수정은 호출함수 자체가 동기인지 비동기인지에 관계없이 비동기함수 호출에만 사용할 수 있도록 wait 키워드를 구현하는 것입니다.
이 버그로 인해 wait를 사용하여 코드 내의 실제 비동기 함수를 호출하는 경우 모든 함수가 비동기 함수로 마크되고 모든 함수 호출이 wait를 사용해야 합니다.
이는 기본적으로 애플리케이션 전체의 모든 기능에 약속의 오버헤드를 추가해야 함을 의미합니다.이 오버헤드는 대부분 비동기화되지 않으며 비동기화되지 않습니다.
실제로 생각해 보면 함수에서 wait를 사용하려면 wait 키워드를 포함하는 함수가 필요합니다.이것은 wait 키워드가 검출된 함수의 처리를 wait 키워드가 일시정지하기 때문입니다.그 함수의 처리가 일시 정지되어 있는 경우는, 확실히 비동기 기능이 아닙니다.
따라서 javascript 및 ECMAScript 개발자에게 다음과 같이 wait/async 구현을 수정해 주십시오.
- wait는 비동기 함수를 호출하는 경우에만 사용할 수 있습니다.
- wait는 동기식 또는 비동기식 모든 함수에서 나타날 수 있습니다.
- 오류 메시지를 "wait is only in async function"에서 "wait is only in async functions"로 변경합니다.
언급URL : https://stackoverflow.com/questions/49432579/await-is-only-valid-in-async-function
'programing' 카테고리의 다른 글
Java가 이미지를 버퍼 이미지로 변환 (0) | 2022.10.22 |
---|---|
python 요청 시간 초과.전체 응답 가져오기 (0) | 2022.10.22 |
MySQL/MariaDB FOUND_ROWS에서 행이 반환되지 않았더라도 1이 반환됨 (0) | 2022.10.22 |
?: PHP의 연산자('Elvis 연산자') (0) | 2022.10.12 |
MySQL 테이블에서 제약을 제거하는 방법 (0) | 2022.10.12 |