'await' 在异步函数中不起作用

chr*_*ris 0 javascript node.js promise async-await

下面的代码给了我以下错误:

语法错误:await 仅在异步函数中有效

async function getLastTransaction() 
{
    paymentsApi.listPayments(locationId, opts).then(function(transactions) 
    {
        if(transactions[transactions.length-1] === undefined)
            return; //no new transaction yet

        var last_transaction_id = transactions[transactions.length-1].id;
        var last_transaction_in_queue; 

        try {
            last_transaction_in_queue = JSON.parse(order_queue[0]).order_id;
        } catch (e) {
            last_transaction_in_queue = order_queue[0].order_id;
        }

        //check if latest transaction is the same as lastest transaction in queue
        if(last_transaction_id !== last_transaction_in_queue) {

            console.log(`new payment...`); 

            var obj = await createTransactionObject(transactions[transactions.length-1], () => {
                order_queue.unshift(obj);
                console.log('new added', order_queue);
            });
}
Run Code Online (Sandbox Code Playgroud)

我不明白这个错误,因为我使用await的是相同的功能,createTransactionObject()但在另一段代码中。

例如,在下面的代码中,我没有收到错误消息,但我await之前还在使用createTransactionObject()

async function populateQueue(transaction_list)  {
    for(var i = 0; i < transaction_list.length; i++) 
    {
        var transaction_json = await createTransactionObject(transaction_list[i], () => {});
        order_queue.unshift(transaction_json);
    } }
Run Code Online (Sandbox Code Playgroud)

Dav*_*vid 5

您需要更改此行:

paymentsApi.listPayments(locationId, opts).then(function(transactions)
Run Code Online (Sandbox Code Playgroud)

对此:

paymentsApi.listPayments(locationId, opts).then(async (transactions) =>
Run Code Online (Sandbox Code Playgroud)

您提供给 .then 的匿名函数需要异步,因为您在其中使用了 await。

您也可以用这个替换该行(也许更好):

const transactions = await paymentsApi.listPayments(locationId, opts);
Run Code Online (Sandbox Code Playgroud)

因为 getLastTransaction 函数是异步的。