问题与callback – OpenWhisk与Nodejs运行时
我正在BlueMix OpenWHisk中开发一个模块,在Cloudant提要发生变化之后,我需要调用一个url来更新另一个平台上的一些细节。 我正在使用nodejs运行时。
问题是我的行动等待,POST请求的结果,以上述url。 如果POST成功,那么我应该执行下一个事件序列。
问题:
-
在执行下一个序列之前如何等待POST请求的结果?
-
是否可以等待并返回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(); }); }
您的请求逻辑有点破裂。 例如,你的承诺永远不会解决,你不听正确的callback。
我build议你切换使用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"}); } }); }
你可以写这样的东西:
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 => {})
分别用于正面和负面的场景。