1

I want to run the function synchronously. In my application the supply source needs to be created before it is assigned to the other data. And the application should only further if this task was fulfilled. Because otherwise it will fail because the other data is created and no SupplySourceId is found (undefinded).

here i want to start the synchronous function (processSupplySource();)

var articleSupplySourceId = processSupplySource();

Function ProcessSupplySource:

function processSupplySource(){
var postJson2 = {};
postJson2.articleNumber = entry['part-no'];
postJson2.name = entry['part-no'];
postJson2.taxName = 'Vorsteuer';
postJson2.unitName = 'stk';
postJson2.supplierNumber = "1002";
postJson2.articlePrices = [];
var articlePrices = {};
articlePrices.currencyName = 'GBP';
articlePrices.price = entry['ek-preisgbp'];
articlePrices.priceScaleType = 'SCALE_FROM';
articlePrices.priceScaleValue = '1';
postJson2.articlePrices.push(articlePrices);

return postSupplySource(postJson2);

Function PostSupplySource

function postSupplySource(postJson2) {

rp({
method: 'POST',
url: url + '/webapp/api/v1/articleSupplySource',
auth: {
    user: '*',
    password: pwd
},
body: postJson2,
json: true
}).then(function (parsedBody) {
    console.log('FinishArticleSupplySource');
            var r1 = JSON.parse(parsedBody);
            console.log(r1.id);
            return r1.id;
})
.catch(function (err) {
    console.log('errArticleSupplySource');
    console.log(err.error);
    // POST failed...
});
}

2 Answers2

0

You can use async/await if you are using node 8 to get that synchronous behaviour you looking for.

Otherwise, you will need to use a library like deasync to wait for the post to complete and return the id.

ashleyr
  • 36
  • 1
  • 3
  • The module deasync looks good. Do you know more about it and can you help me with the approach? –  Aug 11 '17 at 12:41
-1

You can wrap your postSupplySource function in a promise and call the other function when it resolves. This will ensure you have `sourceSupplyId' by the time you run the other functions. Except in case of an error. Something like this:

    function postSupplySource(postJson2) {
    return new Promise(resolve, reject){  //**added
    rp({
    method: 'POST',
    url: url + '/webapp/api/v1/articleSupplySource',
    auth: {
        user: '*',
        password: pwd
    },
    body: postJson2,
    json: true
    }).then(function (parsedBody) {
        console.log('FinishArticleSupplySource');
                var r1 = JSON.parse(parsedBody);
                console.log(r1.id);
                resolve(r1.id); // ** added
    })
    .catch(function (err) {
        console.log('errArticleSupplySource');
        console.log(err.error);
        return reject(err); //*** added
        // POST failed...
    });
});
    }

And then you can call the other function inside it like this:

postSupplySource(postJson2)
.then((supplySourceId) => {
// supplySourceId is available.
// you can call other functions here.
}).catch((err) => {
 console.log(err);
});

Hope I got your question right.

As someone mentioned also, you can use asyc await. As

Mekicha
  • 811
  • 9
  • 21
  • No, one can not use promises to run code synchronously. And no, `rp` already returns a promise, so avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Aug 10 '17 at 17:58
  • @Bergi I didn't mean to say he could use promises to run synchronous code. I was suggesting an alternative way to do that. What do you suggest is the best way to go about it? I'm willing to learn from that too. – Mekicha Aug 10 '17 at 18:00
  • Maybe you didn't intend to say it, but the question asks "*How can I run this function synchronously in node.js*" and your answer starts with "*You can use promise to achieve this.*" :-) – Bergi Aug 10 '17 at 18:03
  • 1
    Yeah, I see. I will reframe that statement) – Mekicha Aug 10 '17 at 18:04