javascript - 如何在node.js中同步运行这个函数

标签 javascript node.js function asynchronous post

我想同步运行该函数。在我的应用程序中 需要先创建供应源,然后再将其分配给其他数据。 只有完成了这项任务,申请才会进一步。 因为否则它将失败,因为创建了其他数据并且未找到 SupplySourceId(未定义)。

这里我想启动同步函数(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...
});
}

最佳答案

如果您使用 Node 8 来获得所需的同步行为,则可以使用 async/await。

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

关于javascript - 如何在node.js中同步运行这个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45618433/

相关文章:

c++ - 如何从 C++ 中自己的定义递归调用类成员函数?

c++ - 函数指针声明

javascript - Ember.js - 渲染模态视图,URL 和父 View 仍然显示

node.js - 当用户登录时,如何仅更改页面的标题栏?

node.js - 使用 Passport.SocketIO cookie 解析器错误

javascript - 如何从html中删除所有属性?

python - 我的 'lowest common multiple' 程序挂起,没有输出答案

javascript - 如何在回调中访问正确的“this”?

javascript - 如何使用 Nan::MakeCallback 将事件从 nodejs 插件发送到 javascript?

javascript - 如何对 vcRecaptchaService.execute() 使用 .then 方法?