2

我正在 BlueMix OpenWHisk 中开发一个模块,在 Cloudant 提要更改后,我需要调用一个 url,它会在另一个平台上更新一些细节。我正在使用 nodejs 运行时。

请求是让我的操作等待 POST 请求的结果到上面提到的 url。如果 POST 成功,那么我应该执行下一个事件序列。

问题:

  1. 如何在执行下一个序列之前等待 POST 请求的结果?

  2. 是否可以等待并返回 POST 请求的结果。

发布我的代码

   /**
  *
  * main() will be invoked when you Run This Action
  *
  * @param OpenWhisk actions accept a single parameter, which must be a JSON object.
  *
  * @return The output of this action, which must be a JSON object.
  *
  */

const util = require('util');
var http = require('http');

function main(params) {

    // Updated the status of the User
    params.status ="updated1";

    var options = {
                host: "myhost.mybluemix.net",
                path: "/addtoimc",
                method: "POST",
                headers: {
                    "Content-Type": "text/plain"
                }
            };


      return {message : addtoIMC(options)};

}

function createRequest(data, options)
{

    return http.request(options, function (res) {
            var responseString = "";

            res.on("data", function (data) {
                responseString += data;
                // save all the data from response
            });
            res.on("end", function () {
                console.log("AAA" + responseString); 
            });
        });
}



function addtoIMC(options)
{
    return new Promise(function(resolve, reject) {
            var req = createRequest("Hello",options);
            var reqBody = "post_data";
            req.write(reqBody);
            req.end();

        });
}
4

2 回答 2

6

您的请求逻辑有点错误。例如,您的承诺永远不会得到解决,并且您没有听取正确的回调。

建议你改用request-promise. 以下应该工作

const request = require('request-promise');

function main(params) {
    return request({
        url: "http://myhost.mybluemix.net/addtoimc",
        method: "POST",
        headers: {
            "Content-Type": "text/plain"
        }
    }).then(response => {
        if(response.success) {
            return Promise.resolved({message: "nice"});
        } else {
            return Promise.rejected({error: "it broke"});
        }
    });
}
于 2017-08-02T14:37:16.657 回答
0

你可以这样写:

function main(params) {
  const http = require('http');

  const inputVariable = params.inputVariableNameToBePassedToThisAction;

  const options = {
    host: "myhost.mybluemix.net",
    path: "/addtoimc",
    method: "POST",
    headers: {
      "Content-Type": "text/plain"
    }
  };

  const createRequest = (options) => {
    const promise = new Promise((resolve, reject) =>{
      http.request(options, function(err, resp) {
        if(err){
          reject(`401: ${err}`);
        }
        else{
          let responseString = "";

          res.on("data", function (data) {
            responseString += data;
            // save all the data from response
          });
          res.on("end", function () {
            console.log("AAA" + responseString);
          });
          resolve(responseString);
        }
      });
    });
    return promise;
  };

  return createRequest(options)
    .then(data => {
      //process data from POST request
      //call next methods if there are any, on positive response of POST request
      const outputVariable = data.someImportantParameterToExtract;
      const resp = {
        keyToUse : outputVariable
      };
      //
      return ({
        headers: {
          'Content-Type': 'application/json'
        },
        statusCode: 200,
        body: new Buffer(JSON.stringify(resp)).toString('base64')
      });
    })
    .catch(err => {
      //stop execution because there is some error
      return ({
        headers: {
          'Content-Type': 'application/json'
        },
        statusCode: 400,
        body: new Buffer(JSON.stringify(err)).toString('base64')
      });
    });
};

您可以编写第一个函数,调用它并.then(data => {}).catch(err => {})分别用于正面和负面的场景尝试一下......

于 2017-08-02T14:57:52.897 回答