JavaScript Promiseについて
asynchronousをやるときに必用なのがpromise。
1. Promiseはあとで実行する関数を保存するオブジェクト。
2. Promise自体は関数を保存するオブジェクトなだけだから、それを作っただけでは関数は起動しない。
3. .then()または.catch()をその作ったpromiseオブジェクトに使うことで、初めてそのpromiseオブジェクトに保存されてる関数が実行される。
4. Promiseを定義するときに、その中には、必ずresolve・reject関数が必用。これらは、そのpromiseがいつ終わるのかを指定する。(実際にはそのpromiseのstateをpendingからfulfilledまたはrejectedに変える。javascriptはpeomiseのstateがfulfilledか、rejectedに変わったら、自動的にそのpromiseを終了させる)
一般的なpromiseの作り方。
const myPromise = new Promise*1;
});
一般的なpromiseの起動のしかた。
promise.then(value => console.log(value))
ちなみに:
fetch()自体は関数だけど、fetchがreturnするのはpromise。だから、fetch("https/somethig")はまだHTTP requestをしない。fetch("https/something").then()を使うことで初めて、network requestをする。
fetchのsample implementationはこんな感じ。
function fetch(url) {
return new Promise*2;
}
};
xhr.onerror = () => reject(new Error("Network Error"));
xhr.send();
});
}
*1:resolve, reject) => {
// Do some asynchronous work...
// If the work is successful, call the resolve function with a value
resolve('Success!');
// If the work fails, call the reject function with an error
// reject(new Error('Something went wrong!'
*2:resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response);
} else {
reject(new Error(xhr.statusText