Skip to content

Commit

Permalink
更新 promise
Browse files Browse the repository at this point in the history
  • Loading branch information
0xcaffebabe committed Mar 20, 2020
1 parent f2bd63c commit ba1f58f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
24 changes: 24 additions & 0 deletions 编程语言/JavaScript/AJAX.md
Expand Up @@ -228,6 +228,30 @@ file.onchange = function(){
}
```

### 使用Promise发送ajax

```js
function query() {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState != 4) {
return;
}
if (xhr.readyState == 4 && xhr.status == 200) {
resolve(xhr.responseText);
} else {
reject(xhr.status);
}
};
xhr.open('get', '/home');
xhr.send();
});
}

query().then(r => console.log(r)).catch(r => console.error(r))
```

## 同源策略

ajax受同源策略限制
Expand Down
11 changes: 11 additions & 0 deletions 编程语言/JavaScript/Node/NodeJs.md
Expand Up @@ -232,13 +232,24 @@ promise
```js
promise
.then(v=>{
// 如果返回Promise,则这个promise是调用下一个then的promise
// 如果不是promise,则就是下一个then的回调函数参数v
return new Promise()
})
.then(v=>{
return new Promise()
})
```

**all与race**

```js
// 所有任务都完成才返回结果
Promise.all([query(),query(),query()]).then(()=>console.log('all mission complete'));
// 任一任务都完成就返回结果
Promise.race([query(),query(),query()]).then(()=>console.log('mission complete'));
```

### 异步函数

```js
Expand Down

0 comments on commit ba1f58f

Please sign in to comment.