代码之家  ›  专栏  ›  技术社区  ›  Rahul Kalidindi

在第一个api调用之后进行第二个api调用将返回数据

  •  0
  • Rahul Kalidindi  · 技术社区  · 6 年前

     const searchVenues = (type) => {
      logger.debug('getVenues : type = ' + type);
    
      const config = {
        url: urlAPIServer + '/venue/available',
        qs: {
          type,
        },
        headers: {
          'x-api-key': dataApiKey
        }
      };
    
      return new BluebirdPromise((resolve, reject) => {
        request.get(config, (err, response, body) => {
          if (err) {
            console.error(err);
            reject(err);
          } else {
            resolve(JSON.parse(body));
          }
        });
      });
    };
    
    const getVenuesWithCuisine = () => {
      logger.debug('getVenuesWithCuisine');
    
      const config = {
        url: urlAPIServer + '/venue/viewvenuewithcuisine',
        headers: {
          'x-api-key': dataApiKey
        }
      };
    
      return new BluebirdPromise((resolve, reject) => {
        request.get(config, (err, response, body) => {
          if (err) {
            console.error(err);
            reject(err);
          } else {
            resolve(JSON.parse(body));
          }
        });
      });
    };
    

    分别调用函数从API获取数据并将其绑定到变量。

    searchVenues(venueType).then((venues) => {
          checkContextTimeout(context);
          conversationContext.venueType = venueType;
          conversationContext.venues = venues;
          context.skill = conversationContext; 
        });
    
        getVenuesWithCuisine().then((venueswithcuisines) => {
          conversationContext.venue_details = venueswithcuisines[0}["venue_details"];
          conversationContext.cuisines = venueswithcuisines[1]["cuisines"];
          conversationContext.venueType = venueType;
          conversationContext.venues = venuesJson.venues;
          continueConversation(request, response, context);
        });
    

    conversationContext.venues = venues 为空。

    如何使这些API调用同步,以便第二个API调用仅在第一个API调用返回数据之后进行。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Keith Rousseau    6 年前

    http://bluebirdjs.com/docs/api/promise.all.html

    Promise.all([searchVenues(venueType), getVenuesWithCuisine()]).then(function([venueResp, cuisineResp]) {
      ...
    });