回调函数的可变范围

时间:2019-04-21 06:41:25

标签: node.js callback

我正在尝试在节点js中使用回调函数,所以我像这样传递变量和回调函数:

if(true){
await this.serialNumber(customer, async serial => {
console.log(serial); // it's log 43435543
});

// I need to use that serial out of the scope of that function by passing it to this new function
await this.storeinDB(customer, serial);
}

// this is the function where pass variable to callback function
async serialNumber(customer, callback){
const serial = "43435543";
callback(serial);
}

有办法吗?

1 个答案:

答案 0 :(得分:1)

像在回调中一样调用另一个函数。由于您不使用Promise使用async/await,因此没有区别。

if(true){
  this.serialNumber(customer, function (serial) {
    console.log(serial); // it's log 43435543
    this.storeinDB(customer, serial);
  });
}

// this is the function where pass variable to callback function
serialNumber(customer, callback){
  const serial = "43435543";
  callback(serial);
}