节点动态参数和从函数到Vars的信息传递

时间:2018-05-21 22:29:36

标签: javascript node.js

假设我有三个变量,每个变量都有一个ID和一个Price。我有ID,以及确定价格的功能。

我希望价格函数是动态的,所以我不必为每个ID写一个if语句。

如何将其传递到价格函数中,然后将价格传递回正确的ID? (即确保它转到t1Price而不是t2Price)。

如果你可以指出我正确的方向,那么奖励积分,所以我不仅限于3个身份证/价格。

var t1ID = 0;
var t1Price = 0;
var t2ID = 0;
var t2Price = 0;
var t3ID = 0;
var t3Price = 0;

//get the ID of order
order.then(function(value){
  if (t1ID == 0) {
    t1TXID = value.result.id[0];
    boughtPrice(t1ID, t1BoughtPrice);  //is this right?
  } else if (t2ID == 0) {
    t2ID = value.result.id[0];
    boughtPrice(t2ID, t1BoughtPrice);
  } else if (t3ID == 0) {
    t3ID = value.result.id[0];
  } else {
 console.log('IDs all full!');
}
//Get price based on ID
function boughtPrice (tradeID, tradeBoughtPrice) {
 var idInfo = api call ({
 ID: tradID
})
idInfo.then(function(value) {
    tradeBoughtPrice = value.result.tradeID.price;
    //I want to write the price back to var t1Price
};

1 个答案:

答案 0 :(得分:1)

嗯,嗯,我不确定我是否正确理解它,试着这样做:

    let dataIn = [{id:123, price:0}];
// and so one to add more just dataIn.push({id:123, price:0})

order.then((v)=>{
    dataIn.forEach((e,i) => {
        let t = dataIn[i];
        if(t.id == 0){
            t.id = v.result.id[0];
            //if you are 100% sure that if there is an Id different than 0 there would be set god price you can do that :
            api.call({ID:t.id}).then((r)=>{
                t.price = r.result.tradeID.price;
            })
        }
    });
});