async/await
Rules
awaitは、Promiseオブジェクトを戻る部分の前にのみ配置できます.このときfetch APIで受信した応答データはPromiseオブジェクトであるため利用可能である.
関数でawaitを使用するには、asyncキーを持つ必要があります.テキストaa出力後 テキスト、{パッチデータ}に を出力
1.text aa出力後
2.{パッチデータ}にテキストを出力する
コールバック関数が定義されていませんcallbackFunction dksdp textInside.
実際に使用するgetData関数の内部で実行する場合、textInsie変数値を使用できます.
この使い方を閉包と言います.
awaitは、Promiseオブジェクトを戻る部分の前にのみ配置できます.このときfetch APIで受信した応答データはPromiseオブジェクトであるため利用可能である.
関数でawaitを使用するには、asyncキーを持つ必要があります.
let text = "aa";
fetch("https://jsonplaceholder.typicode.com/posts")
.then((res) => res.json())
.then((json) => {
text = json;
console.log("text inside", text);
});
console.log("text", text);
コールバック形式でメソッドを作成します.1.text aa出力後
2.{パッチデータ}にテキストを出力する
コールバック関数が定義されていませんcallbackFunction dksdp textInside.
実際に使用するgetData関数の内部で実行する場合、textInsie変数値を使用できます.
この使い方を閉包と言います.
let text = "aa";
function getData(callback) {
let texInside = "bb";
fetch("https://jsonplaceholder.typicode.com/posts")
.then((res) => res.json())
.then((json) => {
callback(json);
});
}
function callBackFunction(json) {
texInside = json;
console.log("text inside", texInside);
}
console.log("text", text);
getData(callBackFunction);
今からaync waitを書きましょう리턴값이 response인 함수에 대해서 await을 사용할 수 있다.
function getData() {
return fetch("https://jsonplaceholder.typicode.com/posts").then((res) =>
res.json()
);
}
async function exec() {
try {
const text = await getData();
console.log("const text ", text);
} catch (error) {
console.log(error);
}
}
exec();
以下thenを使用async function getData(){
return fetch("https://jsonplaceholder.typicode.com/posts").then((res) =>
res.json()
);
}
getData().then(json => console.log(json));
コードが短くなる可能性があります.参考にしましょう.Reference
この問題について(async/await), 我々は、より多くの情報をここで見つけました https://velog.io/@darcyu83/asyncawaitテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol