异步函数 returns 未定义,即使返回了值

Async function returns undefined even though values are returned

我有以下两个函数,一个调用另一个,但记录变量未定义,随后出现错误。我不明白为什么脚本不等待。它似乎只是继续未定义的变量。

async function searchRecord(recordID) {
    client.search({
        index: 'records',
        type: 'record',
        body: {
            query: { match: { _id: recordID } }
        }
    }).then(result => {
        return result
    }).catch(error => {
        console.log(error)
        return []
    })
}

function test(jsonRecord) {
    const userID = jsonRecord.users[0]
    searchRecord(jsonRecord.objectID).then(record => {
        if (record.length === 0) {
            record = jsonRecord
        }
    })
}

我得到的错误是: UnhandledPromiseRejectionWarning: TypeError: 无法读取 属性 'length' of undefined

尝试将 searchRecord 更新为 return:

async function searchRecord(recordID) {
  return client
    .search({
      index: "records",
      type: "record",
      body: {
        query: {
          match: { _id: recordID },
        },
      },
    })
    .then((result) => {
      return result;
    })
    .catch((error) => {
      console.log(error);
      return [];
    });
}

这是异步的,请尝试使用 await

async function searchRecord(recordID) {
  try {
    const result = await client.search({
      index: 'records',
      type: 'record',
      body: {
        query: {
          match: { _id: recordID }
        }
      }
    });
    return result;
  } catch (error) {
    console.log(error);
    return [];
  }
}

你为什么不使用 Promise?如果您想像上面的答案一样使用 async-await 没关系,但是使用 Promise 它变得非常容易

function searchRecord (recordID) {
  return new Promise((resolve, reject)=>{
    client.search({
      index: 'records',
      type: 'record',
      body: {
        query: {
          match: { _id: recordID }
        }
      }
    }).then(
      result => resolve(result)
    ).catch(
      error => {console.log(error);reject());
  });
}


function test (jsonRecord) {
    const userID = jsonRecord.users[0]
    searchRecord(jsonRecord.objectID)
      .then(
        record => {
          if (record.length === 0) {
            record = jsonRecord
          }
        }
      )
  }

函数 client.search() return 是一个承诺。您可以选择 return 来自 searchRecord() 的承诺。然后,在 test() 函数中处理 catch

或者,您也可以通过实现 try catch 块来处理 searchRecord() 中的错误。但在这种情况下,关键是要等待 client.search() 完成,然后才能从 searchRecord() 开始 return。

function searchRecord(recordID) {
    return client.search({
        index: 'records',
        type: 'record',
        body: {
            query: { match: { _id: recordID } }
        }
    });
}

function test(jsonRecord) {
    const userID = jsonRecord.users[0]
    searchRecord(jsonRecord.objectID).then(record => {
        if (record.length === 0) {
            record = jsonRecord
        }
    }).catch(error => {
        console.log(error)
        return []
    })
}

The error that I get is: UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'length' of undefined

原因是 searchRecord() return 的承诺立即解析为 undefinedsearchRecord().

函数中没有return语句