如何根据值更改函数调用

How to change the function call based on value

导入了3个函数:

import { searchShip, searchLcl, searchFcl } from "services/logisticsService";

searchData = {
  currentPort: currentPort,
  destinationPort: destinationPort,
  date: readyTOLoad,
  type: containerType,  // containerType is geting 1 value among this (ship,lcl,fcl)
}

在这里,我想根据 containerType 值调用其中一个函数。例如:

如果我得到的类型值是 ship 那么它应该是

searchShip(searchData).then((response) => {
  console.log(response)
})

如果我得到的类型值是 lcl 那么它应该是

searchLcl(searchData).then((response) => {
  console.log(response)
})

如果我得到的类型值是 fcl 那么它应该是

searchFcl(searchData).then((response) => {
  console.log(response)
})

有没有什么好的方法可以在没有 if else 语句的情况下在该类型条件下调用该搜索函数,因为其中有一个非常漫长的过程来处理响应。

是的,您可以定义一个具有 {[key]: function} 结构的对象。

const handlersByType = {
  ship: searchShip,
  lcl: searchLcl,
  fcl: searchFcl.
};

handlersByType[type](searchData).then((response) => {
  console.log(response)
})