Call flow from within a function node and get a promise returned

Example of how you could create a flow and return a promise. This allows you to use the flow from within a function node and get a promise returned.

[{"id":"3b4b47a5.77a928","type":"inject","z":"316818d1.472f68","name":"inject","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":true,"x":150,"y":120,"wires":[["dbc66e1b.fef19"]]},{"id":"dbc66e1b.fef19","type":"function","z":"316818d1.472f68","name":"getJoke","func":"const getJoke = function (firstname=\"Chuck\", lastname=\"Norris\") {\n    \n    let promise = new Promise((resolve, reject) => {\n        msg.resolve = resolve;\n        msg.reject = reject;\n    });\n    \n    msg.url = `http://api.icndb.com/jokes/random?firstName=${firstname}&lastName=${lastname}`;\n    msg.method = 'GET';\n    \n    node.send(Object.assign({}, msg));\n    \n    return promise;\n};\n\nglobal.set('getJoke', getJoke);","outputs":1,"noerr":0,"x":280,"y":120,"wires":[["7995241c.8025dc"]]},{"id":"7995241c.8025dc","type":"http request","z":"316818d1.472f68","name":"","method":"use","ret":"obj","url":"","tls":"","x":430,"y":120,"wires":[["d502bf3.123474"]]},{"id":"a71e60af.8cb3a","type":"function","z":"316818d1.472f68","name":"getJoke()","func":"const joke = global.get('getJoke')();\n\njoke.then(joke => {\n    node.warn(joke);\n}).catch(error => {\n    node.error(error);\n});","outputs":"0","noerr":0,"x":280,"y":220,"wires":[]},{"id":"d99782c4.32a13","type":"inject","z":"316818d1.472f68","name":"run","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"x":150,"y":220,"wires":[["a71e60af.8cb3a"]]},{"id":"d502bf3.123474","type":"function","z":"316818d1.472f68","name":"resolve","func":"msg.resolve(msg.payload.value.joke);\n\n// reject\n// setTimeout(function () {\n//     msg.reject({message: 'Could not request joke'});\n// }, 2000);","outputs":"0","noerr":0,"x":580,"y":120,"wires":[]},{"id":"6cb62d4c.1bf0e4","type":"comment","z":"316818d1.472f68","name":"use above flow","info":"","x":160,"y":180,"wires":[]}]

Flow Info

Created 7 years, 8 months ago
Rating: 5 2

Owner

Actions

Rate:

Node Types

Core
  • comment (x1)
  • function (x3)
  • http request (x1)
  • inject (x2)

Tags

  • promise
  • promises
  • es6
Copy this flow JSON to your clipboard and then import into Node-RED using the Import From > Clipboard (Ctrl-I) menu option