sample.js
//関数宣言
function add(x, y) {
return x + y;
};
console.log(add(1, 2)); // => 3
//即時関数
(function (x, y) {
console.log(x + y);
}(1, 2)); // => 3
//関数代入
var test = function (x, y) {
return x + y;
};
console.log(test(1, 2)); // => 3
//ラムダ
var test = (x, y) => x + y;
console.log(test(1,2)); // => 3
//配列
var array = [1,2,3]
console.log(array[0]) //=> 1
//連想配列
var array2 = {
a : true,
b : false,
c : false
};
console.log(array2['a']) //=> true
//Promise then 非同期処理
var sample = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve();
}, 1000);
});
sample.then(function(value) {
console.log("Promise成功!");
});
console.log("先に出力");
非同期
asyncとawait
sample.js
const test = async () => {
console.log(1);
await new Promise((resolve) => {
setTimeout(() => {
console.log(2);
resolve();
},1000)
})
}
const main = async () => {
await test();
console.log(3);
}
main()
testからasyncとawaitを外す
sample.js
const test = () => {
console.log(1);
return new Promise((resolve) => {
setTimeout(() => {
console.log(2);
resolve();
},1000)
})
}
const main = async () => {
await test();
console.log(3);
}
main()
mainからもasyncとawaitを外す
sample.js
const test = () => {
console.log(1);
return new Promise((resolve) => {
setTimeout(() => {
console.log(2);
resolve();
},1000)
})
}
const main = async () => {
await test();
console.log(3);
}
main()