传递值时的顺序承诺
Sequential Promises whilst passing values
我在玩弄命运 API,我 运行 遇到了一些问题。如果我请求一个字符的详细信息,它 returns 一个对象,但值是 ID,然后需要将其传递到另一个 API 调用 'the manifest' 其中 returns 一个对象对于那个 ID。
我正在使用 'request-promise' 进行 API 调用,但这意味着我不得不嵌套调用,对此我并不满意。
我需要保留第一次请求的部分数据,然后再调用一次获取最后的数据。
例如:
request('destiny-character-api')
.then(character => {
// Keep some of the data from character, eg className
request(`destiny-manifest-api/${character.item}`)
.then(item => {
// Overwrite character.item with the value of item.name
return item;
});
});
我需要一种方法来推迟第二个请求,直到第一个请求返回,然后将返回值传递给第二个请求。
谢谢
您可以 chain your promises 而不是嵌套调用,如下所示:
request('destiny-character-api')
.then(character => {
return request(`destiny-manifest-api/${character.item}`);
})
.then(item => {
return item;
});
如果您需要将一些数据从第一个成功处理程序传递到第二个,那么 return 一个 Promise.all()
,用您的第二个 request
传递一个数组,以及您要发送的任何数据。例如,
request('destiny-character-api')
.then(character => {
return Promise.all([
request(`destiny-manifest-api/${character.item}`),
character.className
]);
})
.then(([item, className]) => {
item.name = className;
});
如果您不想嵌套调用,您可以return请求承诺并以平面样式继续。
return request('destiny-character-api')
.then(character => {
return request(`destiny-manifest-api/${character.item}`);
}).then(item => {
return item;
});
这样代码就扁平化了。阅读有关承诺链的信息。
不知道你所说的推迟第二个请求是什么意思....在这段代码中,第二个请求将在第一个请求完成后触发。
我在玩弄命运 API,我 运行 遇到了一些问题。如果我请求一个字符的详细信息,它 returns 一个对象,但值是 ID,然后需要将其传递到另一个 API 调用 'the manifest' 其中 returns 一个对象对于那个 ID。
我正在使用 'request-promise' 进行 API 调用,但这意味着我不得不嵌套调用,对此我并不满意。
我需要保留第一次请求的部分数据,然后再调用一次获取最后的数据。
例如:
request('destiny-character-api')
.then(character => {
// Keep some of the data from character, eg className
request(`destiny-manifest-api/${character.item}`)
.then(item => {
// Overwrite character.item with the value of item.name
return item;
});
});
我需要一种方法来推迟第二个请求,直到第一个请求返回,然后将返回值传递给第二个请求。
谢谢
您可以 chain your promises 而不是嵌套调用,如下所示:
request('destiny-character-api')
.then(character => {
return request(`destiny-manifest-api/${character.item}`);
})
.then(item => {
return item;
});
如果您需要将一些数据从第一个成功处理程序传递到第二个,那么 return 一个 Promise.all()
,用您的第二个 request
传递一个数组,以及您要发送的任何数据。例如,
request('destiny-character-api')
.then(character => {
return Promise.all([
request(`destiny-manifest-api/${character.item}`),
character.className
]);
})
.then(([item, className]) => {
item.name = className;
});
如果您不想嵌套调用,您可以return请求承诺并以平面样式继续。
return request('destiny-character-api')
.then(character => {
return request(`destiny-manifest-api/${character.item}`);
}).then(item => {
return item;
});
这样代码就扁平化了。阅读有关承诺链的信息。
不知道你所说的推迟第二个请求是什么意思....在这段代码中,第二个请求将在第一个请求完成后触发。