promise
用途用来解决回调陷阱
最简示例
new Promise(resolve => {
setTimeout(() => {
resolve('hello')
}, 2000)
}).then(res => {
console.log(res)
})
二级回调改写例子
new Promise(resolve => {
setTimeout(() => {
resolve('hello')
}, 2000)
}).then(val => {
console.log(val) // 参数val = 'hello'
return new Promise(resolve => {
setTimeout(() => {
resolve('world')
}, 2000)
})
}).then(val => {
console.log(val) // 参数val = 'world'
})
async
完整单词: asynchronous
async function getData_1 () {
return '100'
}
等效于
function getData_2 () {
return new Promise((resolve, reject) => {
resolve('100')
})
}
await 就是等待 async执行完,才会执行后面的东西, 等待的东西是异步的,它就会阻塞当前代码,
别担心, 它只能在async函数里使用, 虽然阻塞,但是是异步的
async function getData_1 () {
return '100'
}
function getData_2 () {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('200')
}, 2000)
})
}
async function run () {
const data_1 = await getData_1();
console.log(data_1);
const data_2 = await getData_2();
console.log(data_2);
}
run ();
从网页下载json数据
fetch
标准写法
fetch('http://example.com/answer', {answer: 42})
.then(function(response) {
if(response.ok)
{
return response.json();
}
})
.then(
function(jsonData)
{
console.log(json.Data);
}
)
修改 HTTP 头
var url = 'https://example.com/profile';
var data = {username: 'example'};
fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data), // data can be `string` or {object}!
headers: new Headers({
'Content-Type': 'application/json'
})
}).then(
res => res.json()
)
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
await 写法
(async function () {
const data = await (await fetch(dataSource)).json();
}());
async function run()
{
const response= await fetch(url);
if(!response.ok)
{
console.log(reponse);
}
const data=await(response.json());
}