Javascript ES6承诺序列,XHR用于令牌,然后再次XHR
我需要做一个承诺序列。我想使用基于标准的方法(ES6?)。实现这一目标的最佳方式是什么Javascript ES6承诺序列,XHR用于令牌,然后再次XHR,javascript,Javascript,我需要做一个承诺序列。我想使用基于标准的方法(ES6?)。实现这一目标的最佳方式是什么getToken()和httpReq()返回承诺,clock.now只返回now的unix时间戳。我的代码如下所示(简化/浓缩)。我明白我需要用一个单一的捕获物来压扁承诺链。。。有人能用一种干净、易读、不聪明的ES6方式来说明吗 // we don't have a good token so we need to get one first, then GET the resource. getToken(h
getToken()
和httpReq()
返回承诺,clock.now
只返回now的unix时间戳。我的代码如下所示(简化/浓缩)。我明白我需要用一个单一的捕获物来压扁承诺链。。。有人能用一种干净、易读、不聪明的ES6方式来说明吗
// we don't have a good token so we need to get one first, then GET the resource.
getToken(host, port, auth).then(function(token) {
httpReq(method, host, port, path, token).then(function(data) {
console.log(data);
}, function(status) {
console.log(status);
});
}, function(status) {
console.log(status);
});
你很接近。我是这样做的:
getToken(host, port, auth) // Promise for token
.then(token => httpReq(method, host, post, path, token)) // Promise for data, using token
.then(data => console.log(data)) // final step
.catch(err => console.error(err)); // error handling for all steps in the chain
如果没有箭头功能:
getToken(host, port, auth)
.then(function(token) { return httpReq(method, host, post, path, token); })
.then(function(data) { return console.log(data); }) // not strictly necessary. But
// strictly equivalent to above
.catch(function(err) { return console.log(err); });
需要注意的几件事:
- 不要嵌套
子句。相反,从第一个.then()
子句返回一个承诺,并在外部继续该链.then()
- 使用承诺时,确保始终返回承诺。不要让
子句没有返回值,也不要让承诺函数没有返回值.then()
- 使用箭头函数可以使上述两点变得简单
getToken(host, port, auth) // Promise for token
.then(token => httpReq(method, host, post, path, token)) // Promise for data, using token
.then(data => console.log(data)) // final step
.catch(err => console.error(err)); // error handling for all steps in the chain
如果没有箭头功能:
getToken(host, port, auth)
.then(function(token) { return httpReq(method, host, post, path, token); })
.then(function(data) { return console.log(data); }) // not strictly necessary. But
// strictly equivalent to above
.catch(function(err) { return console.log(err); });
需要注意的几件事:
- 不要嵌套
子句。相反,从第一个.then()
子句返回一个承诺,并在外部继续该链.then()
- 使用承诺时,确保始终返回承诺。不要让
子句没有返回值,也不要让承诺函数没有返回值.then()
- 使用箭头函数可以使上述两点变得简单