首页 > 解决方案 > 优化在 NodeJs 中执行链式 API 调用的时间

问题描述

我正在进行第 3 方 API 调用,以便保存和使用注册用户详细信息在每个 API 平台上创建记录。为此,我需要从一个 API 调用中获取数据并使用该数据(数据的属性)在 Nodejs 中进行下一个 API 调用。为此,我将 fetch() 与 Promise 一起使用,如下面的代码示例所示。

// Call the API
fetch('url1').then(function (response) {
    if (!response.ok) return Promise.reject(response);
    return response.json();
}).then(function (url1Response) {
    // Store the url1 response data to a variable for futher use (if required)
    newdata = url1Response;
    return fetch('url2'); // use a property of the first api response to execute next API call.
}).then(function (response) {
    if (!response.ok) return Promise.reject(response);
    return response.json();
}).then(function (url2Response) {
    console.log(newdata, url1Response);
}).catch(function (error) {
    console.warn(error);
}); 

我的代码执行正常,但是执行并最终发送响应需要很长时间,所以我想优化执行时间。

有没有办法以非常优化的方式执行此操作,以使时间复杂度尽可能低?如果有任何节点模块可以解决这个问题,那就太好了。

标签: javascriptnode.js

解决方案


推荐阅读