Introduction to the Fetch API and Promise
Tue, Jun 9, 2020
2-minute read
In this learning note, we’ll learn what the new Fetch API looks like, what problems it solves, and the most practical way to retrieve remote data inside your web page using the fetch() function
有一贴 api 小白技术贴,promise 和 fetch
Promise
let firstFunction = function () {
return new Promise(function (resolve, reject) {
resolve("Hava a nice day");
});
};
console.log(firstFunction());
try console.log to check what happen in website
continue…
let firstFunction = function () {
return new Promise(function (resolve, reject) {
resolve("Hava a nice day");
});
};
let secondFuntion = function (dataFromFirstFunction) {
return new Promise(function (resolve, reject) {
resolve(dataFromFirstFunction + "yoyo");
});
};
console.log(secondFuntion());
shows: [[PromiseStatus]]: “resolved” [[PromiseValue]]: “undefinedcrazy”
let firstFunction = function () {
return new Promise(function (resolve, reject) {
resolve("Hava a nice day");
});
};
let secondFuntion = function (dataFromFirstFunction) {
return new Promise(function (resolve, reject) {
resolve(dataFromFirstFunction + "yoyo");
});
};
firstFunction().then(function (data) {
console.log(secondFunction(data));
});
[[PromiseStatus]]: “resolved” [[PromiseValue]]: “Hava a nice day yoyo”
modify this code:我们需要打出来
firstFunction()
.then(function (data) {
return secondFunction(data); // data:dataFromFirstFunction + 'yoyo'
})
.then(function (data) {
console.log(data);
});
shows get a string:
Hava a nice day yoyo
modify this code:
firstFunction()
.then(function (data) {
return secondFunction(data); // data:dataFromFirstFunction + 'yoyo'
})
.then(function (data) {
alert(data);
});
//shows a alert from chrome
Fetch
now coming to the Fetch
fetch('https://.....')
console.log((fetch('https://.....')))
above shows imformation from the web json.
now delete console.log, continue this code
fetch("https://.....").then(function (response) {
console.log(response);
});
// still show all the information like previous one, but we need to let "fetch" know it is a json file.
fetch('https://.....')
.then(function(response){
console.log(response.json());
})
// add .json
// now the chrome show a little bit more
Promise {<resolved>: {_}}
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Object
events:
in_hand:
meta:
_proto_:Object
need those imformation from promise to string
fetch("https://.....")
.then(function (response) {
return response.json();
})
.then(function (response) {
console.log(response);
});
now it print all the information.
done~~~!