我试图找出一种使用函数式编程编写下面的代码的方法。

let member_found = [];

// going through 50 or more pagination until 5 are found.
while(member_found.length < 5)
{
  let member = findMember(/* calls selenium commands to visit next page */);
  if(member != undefined)
      member_found.push(member);
}

console.log(member_found) // expecting 5 values but actual is 0.


当前,由于js的非阻塞性质,代码进入无限循环。

最佳答案

您可以包装findMember返回承诺,然后可以使用ES6 async \ await功能:)

假设您有findMember(cb)
所以会的

function promiseFindMember() {
    return new Promise((res, rej) => findMember(member => res(member)))
}


这样,您将可以按照以下方式编写函数

function async foo() {
    let members = []
    while(member_found > 5) {
        let member = await promiseFindMember()
        if(member !== undefined) {
            members.push(member)
        }
    }
}


我还添加了一个示例来了解概念并在思想之间进行比较:)



function dummyCb(cb){
  console.log("Dummy run!")
  setTimeout(cb, 1000)
}

function promiseDummyCb(){
  return new Promise((res, rej) => dummyCb(() => res()))
}


async function async_hello() {
  cb_count = 0
  while(cb_count < 5) {
    await promiseDummyCb()
    cb_count += 1
  }
}

async function hello() {
  cb_count = 0
  while(cb_count < 5) {
    dummyCb()
    cb_count += 1
  }
}



hello()

08-19 07:50