首页 > 解决方案 > 节点动态参数和从函数传递信息到变量

问题描述

假设我有三个变量,每个变量都有一个 ID 和一个价格。我有 ID 和计算价格的功能。

我希望价格函数是动态的,因此我不必为每个 ID 编写 if 语句。

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

如果您能指出我正确的方向,则可以加分,因此我不限于 3 个 ID/价格。

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

标签: javascriptnode.js

解决方案


嗯,我不确定我是否理解正确,让我们尝试这样做:

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

推荐阅读