我們希望快速在object裡面拿到相關的值,可以用以下的方式去拿取
const person = {
familyName: "li",
fullName: "Brian li",
age: 25,
};
let hobbies = ['sport1','sport2']
const [hobby1,hobby2] = hobbies;
console.log(hobby1,hobby2);
let callName = ({ familyName }) => {
console.log(familyName, "callNameFn");
};
let { fullName, age } = person;
callName(person);
console.log("i am" + fullName + "my age" + age);
const fetchData = (callback) => {
setTimeout(() => {
callback("Done");
}, 1500);
};
setTimeout(() => {
console.log("timer is done");
fetchData((text) => {
console.log(text);
});
}, 2000);
console.log("hello");
console.log("hi");
// console 結果會是
hello
hi
timer is done
Done
在一些程式碼的狀態下,我們很多時候遇到這種data需要等待的問題,所以我們要用promise去改善這個問題。
const fetchData = (callback) => {
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Done");
}, 1500);
});
return promise;
};
setTimeout(() => {
console.log("timer is done");
fetchData()
.then((text) => {
console.log(text);
return fetchData();
})
.then((text2) => {
console.log(text2);
});
}, 2000);
console.log("hello");
console.log("hi");
執行結果
hello
hi
timer is done
Done
Done
那我們也可以用 async await
去讓我們的程式碼更簡潔一點
const fetchData = (callback) => {
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Done");
}, 1500);
});
return promise;
};
setTimeout(async () => {
console.log("timer is done");
let data = await fetchData();
console.log(data);
}, 2000);
console.log("hello");
console.log("hi");
這一篇其實我只是在寫增加頁數的,希望大家平常都會用到這些小技巧