2016-04-22 139 views
1

在ExpressJS应用程序上使用请求承诺模块时,我想提出两个请求,但我需要从第一个请求产生的响应数据传递到第二个请求。如何将请求响应传递给另一个请求?

我之后的例子就是;

const options = { 
    url: 'http://api.example.com/v1/token', 
    method: 'GET' 
}; 

request(options).then((response) => { 
    request({ 
     url: 'http://api.example.com/v1/user', 
     method: 'POST', 
     data: { token: response.token } 
    }).then((final_response) => { 
     res.send(final_response); 
    }); 
}); 

我已经省略了错误处理以保持示例简短。我的兴趣在于将一个请求的响应传递给另一个请求的技术。

回答

1

您可以通过返回它们来链接承诺。 喜欢的东西:

request(options1) 
    .then((response1) => { 
    return request(options2) 
    }) 
    .then((response2) => { 
    return request(options3) 
    }) 
    .then((final_response) => { 
    res.send(final_response); 
    }); 

这里是一个很好的文章关于promise chaining and error handling

+0

Javascript gods回答了,谢谢:) – MindVox

+0

@Karl没问题:) – Lulylulu

+0

任何想法是如何将响应从第一个请求传递到第二个? – MindVox

相关问题