2017-08-10 41 views
1

我想同步运行该功能。在我的应用程序 中,需要在将其分配给其他数据之前创建供应源。 只有完成此任务,应用程序才会进一步执行。 因为否则它将失败,因为创建了其他数据并且找不到SupplySourceId(未发现)。如何在node.js中同步运行此功能

在这里,我要开始同步功能(processSupplySource();)

var articleSupplySourceId = processSupplySource(); 

功能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); 

功能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... 
}); 
} 
+1

阅读回调或承诺 – yBrodsky

+0

你不能。你不应该这样做。你可以很容易地异步运行它,然后按顺序*。 – Bergi

回答

0

您可以使用异步/ AWAIT如果您使用节点8来获取您要查找的同步行为。

否则,您将需要使用像deasync这样的库来等待帖子完成并返回id。

+0

模块deasync看起来不错。 你知道更多关于它,你可以帮助我的方法吗? – labo28

-1

您可以将您的postSupplySource函数包装在承诺中,并在解析时调用其他函数。这将确保您在运行其他函数时拥有`sourceSupplyId'。除了出现错误。事情是这样的:

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... 
    }); 
}); 
    } 

然后你就可以调用其他的函数内部它是这样的:

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

希望我把你的问题的权利。

正如有人提到,你可以使用asyc await。 由于

+0

不,不能使用promise来同步运行代码。不,'rp'已经返回一个promise,所以避免['Promise' constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-如何对避免-吧)! – Bergi

+0

@Bergi我不是故意说他可以使用promise来运行同步代码。我正在建议一种替代方法来做到这一点。你认为最好的方法是什么?我也愿意从中学习。 – Mekicha

+0

也许你不打算这么说,但问题是“*如何在node.js *中同步运行此功能”,并且您的答案以“*您可以使用promise来实现此目标。*”开始:-) – Bergi